【问题标题】:How can you combine multiple fetchMore functions in Apollo?如何在 Apollo 中组合多个 fetchMore 函数?
【发布时间】:2021-01-06 12:41:53
【问题描述】:

Apollo 可以同时运行多个 fetchMores 吗?

我有一个相对复杂的钩子,它运行两个查询,并在一个数组中返回这些查询的结果,如下所示:

export const useDashboardState = (collection: string) => {
  // Get various parameters from query string
  const [filter, setFilter] = useQueryParam("filter", StringParam);
  const [minDate, setMinDate] = useQueryParam("minDate", StringParam);
  const [maxDate, setMaxDate] = useQueryParam("maxDate", StringParam);
  const [subcollections, setSubcollections] = useQueryParam(
    "subcollections",
    ArrayParam
  );


  ......the business logic of the hook....



   // Conduct Apollo query #1
    const { loading, error, data, fetchMore: fetchMoreOne } = useQuery(gqlQueryOne, {
      variables: {
        minDate: minDate,
        maxDate: maxDate,
      },
      notifyOnNetworkStatusChange: true,
    });


   // Conduct Apollo query #2
    const { loading, error, data, fetchMore: fetchMoreTwo } = useQuery(gqlQueryTwo, {
      variables: {
        minDate: minDate,
        maxDate: maxDate,
      },
      notifyOnNetworkStatusChange: true,
    });


  return {
    // If either result is still loading, return loading
    loading: senateCommitteesLoading || houseCommitteesLoading,
    // Once both data are non-null, concatenate them and return
    data:
      houseCommittees && senateCommittees
        ? [...houseCommittees, ...senateCommittees]
        : null,
    // How can we implement a re-run of this complicated hook that makes multiple queries?
    fetchMoreOne,
    fetchMoreTwo,
  };
};

例如,是否可以将fetchMoreOnefetchMoreTwo 组合成一个触发刷新的函数?如果是这样,那将如何运作?

【问题讨论】:

  • 为什么不使用一个请求运行两个查询?

标签: javascript reactjs graphql apollo


【解决方案1】:

如果我正确理解了您的问题,您可以这样做:

let fetchAll = useCallback(() => {
  if (fetchMoreOne) fetchMoreOne();
  if (fetchMoreTwo) fetchMoreTwo();
}, [fetchMoreOne, fetchMoreTwo]);

【讨论】:

  • 然后我可以从钩子中返回fetchAll 变量吗?
  • @Harry Cramer,如果您正在编写一个自定义钩子,通过查看您的代码看起来很像,那么可以。
猜你喜欢
  • 2017-11-30
  • 2020-03-27
  • 2022-07-21
  • 2020-12-10
  • 2019-08-23
  • 2017-08-30
  • 1970-01-01
  • 2021-02-18
  • 2014-04-14
相关资源
最近更新 更多