Search code examples
reactjsgraphqlreact-apolloapollo-clientreact-apollo-hooks

UseApolloClient query won't return fetchMore


I am working on project with Apollo on client side. I am using react-apollo-hooks on my client side. And I have a problem with useApolloClient.

When i fire query with my client I got in useApolloClient I don't get back all data I need. FetchMore is missing. If I use regular query (useQuery) I get that. But problem is I need to fire that query on click and i need to use one provided with apollo client.

I have this function for fetching data on click:


    const bulkSearch = async data => {
        setContent(<Spinner />);
        showModal();

        try {
          const response = await client.query({
            query: BULK_SEARCH_PRODUCTS,
            variables: { data }
          });

          if (!response.loading) {
            setContent(
              <ProductsListDisplay
                products={response.data.bulkSearch.products}
                fetchMore={response.fetchMore}
                count={{ total: 10 }}
              />
            );

            return 200;
          }
        } catch (err) {
          return 400;
        }
      };

And response doesn't contain fetchMore.

On the other way classic query returns fetchMore.


    const newdata = useQuery(BULK_SEARCH_PRODUCTS, {
        variables: { data: { ids: ["536003", "513010"] } }
      });

Some help ? Thank you!


Solution

  • According to the apollo-client docs, ApolloClient.query returns a Promise that resolves to an ApolloQueryResult, which is a simpler object that has only data, errors, loading, networkStatus, and stale as properties.

    On the other hand, the render prop argument of react-apollo's Query component gets fed a much richer object, with fetchMore being one of its additional properties. If you want to do something similar using the raw ApolloClient object, you would have to use ApolloClient.watchQuery, which returns an ObservableQuery that you can subscribe to consume results. The benefit of this is that you have access to more methods, such as ObservableQuery.fetchMore.

    Note this approach is fundamentally different than using ApolloClient.query, since that function requests one query and returns the result as a Promise, while ApolloClient.watchQuery consistently monitors your cache and pushes updated results to your subscribe method when the cache store changes, so it's a more complicated lifecycle. In general, if you're already using react-apollo or one of the @apollo/react-X packages, you probably want to stay away from ApolloClient.watchQuery, since the functionality from those libraries builds directly on top of it and is designed to be easier to consume.

    Hope this helps!