In production, mutations aren't going to happen instantly. We can improve the UX by rendering the intended result before the actual mutation happens
In this lesson, we will learn how to handle optimistic updates by simulating an internet connection with a setTimeout
and using optimisticResponse
from the useMutation
composable to handle the update.
Kevin Cunningham: [0:00] With our current form, when we update this from, say, 120 to 12, it updates immediately, but think about what happens. We are sending a request to the server and waiting for the server to return and say, "Yep, I've got that" before our data's updated.
[0:17] Because our server and our frontend are on the same machine at the moment, we're not seeing any impact on that delay, so let's create a delay.
[0:27] In my controller for my backend GraphQL endpoint, before I return the update, we're going to await for a new Promise. I'll just use the resolve property. We'll set a timeout, and we'll resolve after two seconds.
[0:44] We're doing all the work that we're doing to update the craft. Then we're waiting for two seconds. Only then are we sending back to our frontend.
[0:52] Let's change the age from 12 months to 120 months. We'll update, one, two, and we're there.
[1:05] The first problem is that that form, once we've clicked that Update button, we don't want to wait around. Let's emit a close as soon as we submit that form. Let's change it from 120 back to 12 again and update. One, two, and then our data gets back to where it needs to be.
[1:26] The next problem is that we have still data on our page, and worse, it's still data that the user themselves have inputed, so they know it's wrong. How can we fix that?
[1:37] In our useMutation, when we return our variables, we can also return an optimisticResponse. This optimisticResponse is going to happen when we update the craft.
[1:56] What do we want that to be? We want it to be the current state of the updateFields, so that would be the id, the name, the type. All of those is what we'd be expecting to have back again. Let's see what happens now.
[2:13] We update, let's change this to 120. We click Update, it closes. Our UI goes to 120, and that flash was during a refresh of data. We're using the user-generated data. We're then refreshing the cache, which causes a slight flash of the UI in this instance, but those events are separate.
[2:36] I'll change it again so you can watch for it. We're closing, we're updating the UI, and then watch. After about two seconds, we get that flash because we have the refresh of the data.