首页 > 解决方案 > 如何在 Apollo 中组合多个 fetchMore 函数?

问题描述

是否可以使用 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,
  };
};

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

标签: javascriptreactjsgraphqlapollo

解决方案


如果我正确理解了您的问题,您可以简单地执行此操作:

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

推荐阅读