How To Refresh GraphQL Data After Mutation In Apollo Client

GraphQL

03/11/2022


Imagine this: you have queried data and you just performed a mutation that alters the queried data. Naturally, you want the data to update after said mutation.

JAVASCRIPT
// `data` stays the same after `deleteEvent` is called.
const { data } = useQuery(EventsDocument)
const [deleteEvent] = useMutation(DeleteEventDocument)

By default, this will not happen. To enable it, you need to specify in the mutation's options field refetchQueries the appropriate values, i.e. the GraphQL document and query name.

JAVASCRIPT
// `data` updates after `deleteEvent` is finished executing.
const { data } = useQuery(EventsDocument)
const [deleteEvent] = useMutation(DeleteEventDocument, {
refetchQueries: [
{ query: EventsDocument }, // Document node object used in the query
"events", // Name of the query
],
})

WRITTEN BY

Code and stuff