Okay, okay, I know exactly what you're thinking. Daniel, what if we optimistically update some data, but the server doesn't respond the way we expect it to? There's a database query problem, a connection issue, the user's internet taps out for a moment, whatever. Well, over in 10 optimistic update rollbacks, let me show you how to handle that use case.
Inside of our own mutate hook, We've added this line to get the old product from the cache right before optimistically updating the cache with the new product. Then we return both the old product and the new product from this onMutate function for use in an onErrorHook. e. the promise is rejected.
It takes in the actual error that was thrown, as well as the product that was passed to the mutation, and here is that context that we've returned from the onMutate hook. This gives us the opportunity to do whatever we'd like, maybe report our error to some error reporting service, but most importantly, alert the user that something has gone wrong. This could of course be whatever kind of messaging or alerting system that your app has, It doesn't have to be the browser native alert. Then we do a little bit of a unexpected thing here.
We check to see what product is currently in the cache for that key. Why is this important? Well, we need to check, is the product that's currently in the cache the same one as we put in the cache for the optimistic update? In our case, it should always be But in some more complex apps, maybe another query replaced the product in the cache at some other point in time.
So we want to be sure that we're rolling back the update that we made, not the update that some other part of the app made. Then finally, if indeed it actually is our optimistic update, we set the cache data for that key back to the data of the old product. What does that look like in the browser? Well, let's visit the page for it.
Open up the Bluetooth headphones again and this time turn off our network to simulate a user whose computer has gone offline This time when I update the value of the product title hit enter Yes, you can see the name updates locally to this new value, but we failed to reach the server No problem our on arrow hooks and fires. We alert the user that there was an issue updating the product and then the local state in the cache is reverted back to the previous value.