Apollo useLazyQuery反复调用

问题描述 投票:1回答:1

我正在尝试构建可用于表上任何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个回答
0
投票

对于调用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>);

© www.soinside.com 2019 - 2024. All rights reserved.