【问题标题】:Apollo useLazyQuery repeatedly calledApollo useLazyQuery 反复调用
【发布时间】:2020-05-31 23:42:29
【问题描述】:

我正在尝试构建一个可用于对表进行任何 CRUD 操作的表单。对于更新操作,我想将变量与路由一起传递。所有这些都工作正常,但是当我使用惰性查询调用查询时,它对前几次调用什么都不做,然后在第三次调用时返回数据。这正常吗?我是否调用了错误的查询?有没有办法等待查询返回数据?

import React, { useState, useEffect } from "react";
import Router, { useRouter } from "next/router";

import Container from "react-bootstrap/Container";

import { useLazyQuery } from "@apollo/react-hooks";
import { GET_PLATFORM } from "../graphql/platforms";

export default function platformsForm(props) {
  const router = useRouter();

  // grab the action requested by caller and the item to be updated (if applicable)
  const [formAction, setFormAction] = useState(router.query.action);
  const [formUpdateId, setFormUpdateId] = useState(router.query.id);

  const [
    getPlatformQuery,
    { loading, error, data: dataGet, refetch, called }
  ] = useLazyQuery(GET_PLATFORM, {
    variables: { id: formUpdateId }
  });

  useEffect(() => {
    console.log("update");
    // var dataReturned = getPlatformLookup(formUpdateId);

    !called && getPlatformQuery({ variables: { id: formUpdateId } });
    if (dataGet && dataGet.Platform.platformName) {
      console.log(
        dataGet.Platform.platformName,
        dataGet.Platform.platformCategory
      );
    }
  }),
    [];

  return (
    <Container>
      <h4>
        Name: {dataGet && dataGet.Platform.platformName}
        <br />
        Cat: {dataGet && dataGet.Platform.platformCategory}
        <br />
        formAction: {formAction}
        <br />
        formUpdateId: {formUpdateId}
        <br />
      </h4>
    </Container>
  );
}

【问题讨论】:

    标签: react-apollo react-apollo-hooks


    【解决方案1】:

    要调用 useLazyQuery,您需要使用 useEffect 并传递空数组 [],这样您就可以只调用一次查询,这在您的代码中已经完成(您的 useEffect 中有语法错误,)失踪)。 此外,您不能在 useEffect 回调内部使用从 lazyQuery 返回的数据 (dataGet)。

    你应该这样做:

    // this useEffect hook will call your lazy query exactly once
    useEffect(() => {
        getPlatformQuery({ variables: { id: formUpdateId } });
    
      }, []);
    
    // you can fetch your data here (outside of the useEffect Hook)
    if (dataGet && dataGet.Platform.platformName) {
          console.log(
            dataGet.Platform.platformName,
            dataGet.Platform.platformCategory
          );
     }
    return(<Container>
          <h4>
            Name: {dataGet && dataGet.Platform.platformName}
            <br />
            Cat: {dataGet && dataGet.Platform.platformCategory}
            <br />
            formAction: {formAction}
            <br />
            formUpdateId: {formUpdateId}
            <br />
          </h4>
        </Container>);
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 1970-01-01
      • 2021-07-15
      • 2020-02-27
      • 2021-05-07
      • 1970-01-01
      • 2020-01-07
      • 2020-11-08
      • 2020-05-18
      相关资源
      最近更新 更多