React Query and optimistic updates

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
No comments yet. Be the first to comment.
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

In the previous article, we looked at React Query Mutations, which are great for updating the data once we receive a mutation callback.
However, how great would it be if we could do an optimistic update to make our application even faster?
Let's see what that even means?
We'll have the original list of Pokemon we saw yesterday, and once we decide to add a new Pokemon to this list, we fire an API request.
At the same time, we ask React Query to add this Pokemon already and not care if the mutation was correct or not.
The only thing we would care about is if it failed for some reason. In that case, we should revert to its previous state.
Alright let's start with the mutation we had in the previous article:
const {mutate: addNewPokemon} = useMutation(
(newPokemon) => {
// return axios.post('API', newPokemon);
return {name: newPokemon};
},
{
onSuccess: async (newPokemon) => {
queryClient.setQueryData('pokemon', (old) => [...old, newPokemon]);
},
}
);
Instead of this onSuccess callback, we can leverage the onMutate option.
This option gets fired right away and doesn't care about the state of the actual mutation.
onMutate: async (newPokemon) => {
await queryClient.cancelQueries('pokemon');
const previousPokemon = queryClient.getQueryData('pokemon');
queryClient.setQueryData('pokemon', [
...previousPokemon,
{ name: newPokemon },
]);
return { previousPokemon, newPokemon };
},
Let's see what's going on here. We first cancel the existing query so React Query won't start updating it in between us trying to set it manually.
Then we get the current data object for this query. And manipulate it, as we did before.
Then we return the previous data. This return context can be accessed in the onError function.
Speaking off the error function, this function gets triggered if the mutation fails.
It will get the context from the onMutate return object.
What we want to do is reset the previous state.
onError: (err, newPokemon, context) => {
queryClient.setQueryData('pokemon', context.previousPokemon);
},
Let's complete the function by introducing a failing request. What should happen when we run this function:
onMutate temporary adds the new Pokemon to the listonError gets called, and we reset the stateconst {mutate: addNewPokemon} = useMutation(
async (newPokemon) => {
const request = await fetch('https://pokeapi.co/api/v2/pokemon', {
method: 'POST',
data: {pokemon: newPokemon},
});
const {results} = await request.json();
return results;
},
{
onMutate: async (newPokemon) => {
await queryClient.cancelQueries('pokemon');
const previousPokemon = queryClient.getQueryData('pokemon');
queryClient.setQueryData('pokemon', [...previousPokemon, {name: newPokemon}]);
return {previousPokemon, newPokemon};
},
onError: (err, newPokemon, context) => {
queryClient.setQueryData('pokemon', context.previousPokemon);
},
}
);
I've also created this Code Sandbox environment so you can try it out directly.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter