Delete Mutation after results to update client cache

I am making really good headway implementing the generated mutations within my app (React). I am using the Apollo Client Hooks (currently 3.1.4). I thought I was going to have to do some long tedious cache update functions, but for the most part (after reenabling caching) the cache gets auto updated as long as I retrieve the data back from the mutation that is needed for the cache update.

For one use case I have users able to give different reactions to a comment. And now with the update mutation I can allow a user to change their reaction and the cache auto updates. :smiley:

However, I have run into now where I will have to manually update the cache—on deletes. If a user desides to remove their reaction the cache is not updated. I can make a request to read the data, but that is pre-delete so it doesn’t update anything. I am trying to figure out the best way to handle cache updates on deletes.

Does anybody else have any pointers to get me headed in the right direction here.

:bulb:

What about possibly making a custom hook that adds on a update function that grabs the mutation results and evicts them from the cache and then runs the garbage collector to clean up any dangling references. Then when I want to run a delete mutation and update the cache I will call my custom hook in place of the useMutation hook.

const useDelete = (MUTATION, options = {}) => {
  options.update = (cache, results) => {
    const data = results.data || {}
    for (const [, m] of Object.entries(data) {
      for(const [, r] of Object.entries(m)) {
        if (Array.isArray(r)) {
          r.forEach(i => {
            const id = cache.identify(i)
            cache.evist({ id })
          })
        }
      }
    }
    cache.gc()
  }
  return useMutation(MUTATION, options)
}

UPDATE, This works! Just be sure that you only use delete mutations with this or else you will end up deleting data from your cache unintentionally. For this to work the delete mutation needs to return the id of the deleted object(s). If your id is anything other than _id or id you may need to configure your apollo client to map your ids.

Thoughts? Any react experts? This is sort of off topic, but something that anyone developing with the GraphQL endpoint and react will run into.