Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert apollo client fetchMore updateQuery to apollo cache merge function?

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.

like image 588
user3328991 Avatar asked Nov 07 '22 05:11

user3328991


1 Answers

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/

like image 100
Waweru Kamau Avatar answered Nov 16 '22 17:11

Waweru Kamau