In this article, I'm going to share how I update the my app UI after a mutation by providing an upload function to useMutation.
I am right now developing an application using GraphQL and Apollo Client, which has form where user can register their favourite piece of clothes.
After a successful register, user will be navigated to a 'wardrobe' page, where all the registered pieces are displayed.
wardrobe page↓
But If I just implement register piece function using useMutation, like below, users won't see the piece that they just registered unless they reload the page.
const [registerPiece] = useMutation<RegisterPieceMutationData>(REGISTER_PIECE_MUTATION);
This is because it doesn't refetch all the pieces of clothes data every time users visit the wardrobe page. It obtains the data from Apollo Client cache that is stored the last time it fetched the data from GraphQL server.
So I need to rewrite the cache every time user registered the piece. But How?
Using Refetch Query?
There are several ways to rewrite the cache.
The easiest way is to use refetchQueries
.
const [addTodo, { data, loading, error }] = useMutation(ADD_TODO, {
refetchQueries: [
GET_POST,
],
});
The code above is from the Apollo Client official documentation.
As shown in code above, you can put refetchQueries array in mutation's option.
This enable app to refetch a GET_POST
query after performing ADD_TODO mutation and that rewrite the cache as a result.
in My Case↓
const [registerPiece] = useMutation<RegisterPieceMutationData>(REGISTER_PIECE_MUTATION, {
refetchQueries: [
{
query: GET_WARDROBE_QUERY, //refetch all the pieces data
},
],
});
While the use of a refetch query is straightforward and useful, it comes with the downside of extra network requests. This can result in suboptimal performance due to the increased load times and data usage.
So I decided to use update function instead, which I will explain in the part2.
Top comments (0)