Learn how to use the mutate
function returned from useSwr(key)
to update the client-side cache's value for the given cache key.
Sam Selikoff: [0:00] This Todo app currently is built with a pessimistic UI, which means if I type in a Test todo and hit Enter, the UI waits until the new data is persisted to update the list. We can see if I type in more Todos, this can leave the experience feeling slow because it depends on the network. We can make this UI updates optimistic by using SWR.
[0:23] Let's come down to our createTodo() function. The mutate function that we get back from our call to use SWR is how we update the cash on the client. Right now, we're passing in an async function. First, we await the post request before updating the cache. Let's comment this out. Instead, call mutateTodos() with asynchronous function that optimistically updates the cache.
[0:53] We can come down here, grab this old code. Now, instead of returning the JSON from the server, we can use our local newTodo which we have here stored in React state. We'll replace this with newTodo. Let's go ahead and reset our server and try it out.
[1:22] We saw the todo appear but then it disappeared. If we pop open the network inspector, we can see why. When we enter some new text and hit Save, we see a GET request go out. That's because by default, the mutate function will re-validate the local cached value for this cache key. Since we haven't persisted the new data yet, the get request comes back with the old data.
[1:47] We can disable this validation by passing in false as a second parameter to mutate. Now we see the initial GET request and if we come over here and type in Test and hit Enter, we see our newTodo added to the list.
[2:02] We don't see any re-validation and so now we can keep adding todos. We'll notice already that the UI feels more responsive since it doesn't need to wait for the post request to come back before updating the list.
[2:15] If we check out the console, we're going to see an error. Each child in a list should have a unique "key" prop. This is because in our JSX, we're using the id of a todo as its key but now that we're appending this newTodo that doesn't have an id, we're seeing this error.
[2:36] Let's give our localTodo a temporary ID. We'll say let tempId = v4(), where v4 is a UUID function from the UUID library here. Now we have a unique id for this newTodo. We can come here, copy its properties, and give it an id of tempId.
[3:01] Now, if we try to add a new todo of test, we see it appended to the list, and we don't see that error anymore.