How to handle mutation in Apollo React

mohit thakur
2 min readMay 2, 2021

Are you struggling to reflect changes done by mutations in your component state.

We will try adding a new TODO and 2 different ways to achieve this

  • Call refetch function
  • use refetchQueries with effects

Refetch

You can use Refetch function exposed by UseQuery hook to get latest todo list in your component and the UI will update accordingly

const [todo, settodo] = useState<TODO[]>([);const { loading, data, error, refetch } = useQuery(GET_TODOS)const [addTodo] = useMutation(ADD_TODO);

In above code sample , after you call addTodo you can call refetch
this will bring the latest data from the server and update your cache.

This is not the best way but works.

addTodo({variables:{
item:{name:'dummy'}
}).then((res)=>{
// mutation complete now refetchrefetch()
})

RefetchQueries

Using RefecthQueries, the advantages are that every component using the queries, gets the updates. You don’t have to worry about calling refetch and chances are you don’t have access to refetch function for all queries, you want to update

const [todos, settodos] = useState<TODO[]>([);
const [addTodo] = useMutation(ADD_TODO);
const { error, data } = useQuery(GET_TODOS, {
fetchPolicy: "cache-first",
});
// update state of component whenever query data changesuseEffect(() => {
if (!!data) {
setTodos(data)
}
}, [data]);
// call mutation and add refetchQueries array to mutation optionsaddTodo({variables:{
item:{name:'dummy'},
refetchQueries: [{ query: GET_TODOS }],
})

This piece of code does the trick refetchQueries: [{ query: GET_TODOS }]

This array will recall all the queries that need update after the mutation, the only condition is the component using this query must be mounted.

That is alright because whenever the component will mount again it will get the updated data.

Happy Coding

--

--