How to convert apollo client fetchMore updateQuery to apollo cache merge function?
Asked Answered
M

1

6

I am learning apollo and graphQL and have a simple application that displays a list of data, with a fetchMore function that adds to the array.

I would like to remove the updateQuery as it is being deprecated and use the new field policy merge function. The current cache setup and updateQuery looks like this:

const cache = new InMemoryCache({
  typePolicies: {
    client_client: {
      fields: {
        // add local only value to clients
        isEdited: {
          read(value = false) {
            // when writing the new value return new value or false as default
            return value;
          },
        }
      }
    }
  }
});
  const onFetchMore = () => {
    fetchMore({
      variables: {
        offset: page
      },
      updateQuery: (previousResult, { fetchMoreResult, queryVariables }) => {
        return {
          ...previousResult,
          client_client: [
            ...previousResult.client_client,
            ...fetchMoreResult.client_client,
          ],
        };
      },
    });
  }

However I cannot seem to get it to work as a merge function within the cache for apollo client v3. I have tried adding the merge in many different places however it always seems to break the application.

Any help on how to do this would be appreciated.

Mcgehee answered 21/8, 2020 at 12:52 Comment(0)
B
2

According to the docs, define field policy within the typePolicies option provided in the InMemoryCache constructor:

const cache = new InMemoryCache({   typePolicies: {
    Query: {
      fields: {
        feed: {
          // Don't cache separate results based on
          // any of this field's arguments.
          keyArgs: false,
          // Concatenate the incoming list items with
          // the existing list items.
          merge(existing = [], incoming) {
            return [...existing, ...incoming];
          },
        }
      }
    }   } })

Then you just pass the offset and limit to the initial query:

const { loading, data, fetchMore } = useQuery(GET_ITEMS, {
  variables: {
    offset: 0,
    limit: 10
  },
});

and fetchMore to get the next iteration:

fetchMore({
  variables: {
    offset: 10,
    limit: 10
  },
});

Checkout the docs here: https://www.apollographql.com/docs/react/pagination/core-api/

Bohn answered 31/5, 2021 at 10:38 Comment(2)
where do you get the value of fields: 'feed' ?Wasserman
@Wasserman the fields is a map that specifies the modifier function to call for each modified field. So "feed" here is a query field returned by graphql query, i.e ... query Feed($offset: Int, $limit: Int) { feed(offset: $offset, limit: $limit) { ... Bohn

© 2022 - 2024 — McMap. All rights reserved.