Pagination with Multiple Queries of the Same Field Name Overwriting Each Other

Following the Paginations Docs, I was able to get pagination working well:

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        feed: {
          keyArgs: [],
          merge(existing, incoming, { args: { offset = 0 }}) {
            // Slicing is necessary because the existing data is
            // immutable, and frozen in development.
            const merged = existing ? existing.slice(0) : [];
            for (let i = 0; i < incoming.length; ++i) {
              merged[offset + i] = incoming[i];
            }
            return merged;
          },
        },
      },
    },
  },
});

However, if I’m making another separate query but for the same field (using the code above as an example, “feed” is being queried more than once, aside from fetchMore), the two results get merged in.

I was able to “fix” this by using fetchPolicy: "no-cache" with the second query (useQuery), but is there any way to avoid this without needing to use fetchPolicy: "no-cache"?

Hi! I’m assuming the two separate feed queries each have a different set of variables to distinguish them from each other? If so, you need to list the variable names that are not part of the pagination variables in the keyArgs array. So e.g. if the feed query has a foo variable, keyArgs needs to be [foo]. See here for more information.

If instead both queries are the same (only perhaps with different selection sets), rather than merging existing and incoming, you could perhaps simply return incoming if offset is 0, on the assumption that this would not be a pagination query.

2 Likes