Use Update Callback in useMutation to Manage Cache

  • update function runs after mutation
  • use update callback to manage cache
  • callback function is given a reference to the cache and the data returned by the mutation as parameters
  • uses readQuery and writeQuery functions to work with cached data1

Example for logged in user:

const [ login, result ] = useMutation(LOGIN, {
onError: (error) => {
setError(error.graphQLErrors[0].message)
},
update: (store, response) => {
const dataInStore = store.readQuery({ query: LOGGEDIN_USER })
store.writeQuery({
query: LOGGEDIN_USER,
data: {
...dataInStore,
me: {
...response.data.me
}
}
})
}
})

Example keeping books list updated after adding new book:

const [ createBook ] = useMutation(CREATE_BOOK, {
onError: (error) => {
return setError(error.graphQLErrors[0].message)
},
update: (store, response) => {
const dataInStore = store.readQuery({ query: ALL_BOOKS })
store.writeQuery({
query: ALL_BOOKS,
data: {
...dataInStore,
allBooks: [ ...dataInStore.allBooks, response.data.addBook]
}
})
}
})

  1. Apollo Client Docs: readQuery and writeQuery