如何在Apollo Client React中获取多个条件查询?

我正在使用Apollo Client,并且为了获取查询,我使用了useQuery软件包中的@apollo/react-hooks

我想完成以下任务:

步骤列表:

步骤1:获取查询stage

const GetStage = useQuery(confirmStageQuery,{
  variables: {
    input: {
      id: getId.id
    }
  }
});

第2步:根据我们从GetStage获得的响应,我们希望在2个独立的查询之间进行切换

if (!GetStage.loading && GetStage.data.getGame.stage === "Created") {
  Details = useQuery(Query1,{
    variables: {
      input: {
        id: getId.id
      }
    }
  });
} else if (!GetStage.loading && GetStage.data.getGame.stage === "Confirmed") {
  Details = useQuery(Query2,{
    variables: {
      input: {
        id: getId.id
      }
    }
  });
}

第3步:同样,每次页面加载时,我都会重新获取数据。

useEffect(() => {
  //Fetch for Change in the Stage
  GetStage.refetch();

  //Fetch for Change in the Object
  if (Details) {
    Details.refetch();
    if (Details.data) {
      setDetails(Details.data.getGame);
    }
  }
});

问题?

  

与上次渲染相比,渲染了更多的钩子。

     

Details.data未定义

那么我们如何在Apollo Client中调用多个异步查询?

ppwpp 回答:如何在Apollo Client React中获取多个条件查询?

正如菲利普所说,您不能有条件地调用钩子。但是,有条件地调用查询非常普遍,因此Apollo允许您使用skip选项跳过查询:

const { loading,error,data: { forum } = {},subscribeToMore } = useQuery(GET_FORUM,{
  skip: !forumId,fetchPolicy: 'cache-and-network',variables: { id: forumId },});

该挂钩被调用,但查询未被调用。在我看来,这比对您的用例使用惰性查询要简单和清楚得多。

,

The rules of hooks说,无论何时您发现自己想在钩子周围使用if / else时,就无法有条件地调用钩子。

您要在此处使用lazyQuery来处理所有“可选”或以后将要提取的内容-或用于依赖于另一个查询结果的查询。

这是一个简单的示例(可能不够完整,无法使您的整个代码正常工作):

// This query is always called,use useQuery
const GetStage = useQuery(confirmStageQuery,{
  variables: {
    input: {
      id: getId.id
    }
  }
});

const [fetchQuery1,{ loading1,data1 }] = useLazyQuery(Query1);
const [fetchQuery2,{ loading2,data2 }] = useLazyQuery(Query2);

// Use an effect to execute the second query when the data of the first one comes in

useEffect(() => {
  if (!GetStage.loading && GetStage.data.getGame.stage === "Created") {
    fetchQuery1({variables: {
     input: {
        id: getId.id
      }
    }})
  } else if (!GetStage.loading && GetStage.data.getGame.stage === "Confirmed") {
    fetchQuery2({variables: {
     input: {
        id: getId.id
      }
    }})
  } 
},[GetState.data,GetStage.loading])
本文链接:https://www.f2er.com/3076977.html

大家都在问