Fetchmore and deletion ( Apollo Client cache policy)

Hi all,

I am using fetchMore from the useQuery() hook to achieve some click to load more functionality.

For example, I want to make a long job list and I can also delete the job items.

Here is what I do according to apollo client pagination core api and the cache documentaiton:

//in JobList.tsx

const {data, loading, error, fetchMore} = useQuery(GetAllJobsCursorPaginated)

so I define the merge function in typePolicy in cache, somehow like this:

// in client.ts

const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {    
        getAllJobsCursorPaginated: {
          keyArgs: false,
          merge(existing, incoming) {
              .... // implementing merging logic
                return [...existing, ...incoming] // this is for fetchMore
          }
       ...

But in the meanwhile, but I also want to delete some records, so I use a delete Mutation, and also set a update function for the

//in JobList.tsx

...
const [deleteJob] = useMutation(DeleteJob)
...

const onClickDelete = async (_id: string) => {
  await deleteJob({
    variables: {_id},
    update: (cache) => {
       const data = ... // implementing the deletion logic
      cache.writeQuery({query: getAllJobsCursorPaginatedQuery, data})
    }
  })
}

However, the problem is with the deletion, it always works as fetchMore: take the result after deletion and append it to “existing”…

How can I configure the deleteJob Mutation correctly?

Thanks for any suggestion!

Hi @Conny_Gu :wave: would cache.modify suit your use case better? From the docs:

  • Like writeQuery and writeFragment, modify triggers a refresh of all active queries that depend on modified fields (unless you override this behavior by passing broadcast: false).
  • Unlike writeQuery and writeFragment:
    • modify circumvents any merge functions you’ve defined, which means that fields are always overwritten with exactly the values you specify.
    • modify cannot write fields that do not already exist in the cache.

This would allow you to bypass the merge function and allow you to define another function to filter out deleted entries from your getAllJobsCursorPaginated list. Hope that helps!

1 Like

Hi @JeffAuriemma , thanks! thanks! thanks! Cache.modify is exact what I need! :smiling_face_with_three_hearts:

1 Like