Harrison Cramer
Harrison Cramer

Reputation: 4506

How can you combine multiple fetchMore functions in Apollo?

Is it possible to run multiple fetchMores at the same time with Apollo?

I've got a relatively complicated hook that runs two queries, and returns the results of those queries in a single array, like so:

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,
  };
};

For example, would it be possible to combine the fetchMoreOne and fetchMoreTwo into a single function that would trigger a refresh? And if so, how would that work?

Upvotes: 3

Views: 202

Answers (1)

Sam R.
Sam R.

Reputation: 16460

You can simply do this if I understood your question properly:

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

Upvotes: 1

Related Questions