SWR
Fixing Optimistic UI issues
Now we are going to fix that unstable UI issue. For that, replace the last mutate() call in the addTodo function with the following:
// get the newly add to do
const newTodo = await addRes.json();
// replace above with the fake todo item
mutate('/api/todos', (existingData) => {
const newData = []
for (const item of existingData) {
if (item.id === fakeItem.id) {
newData.push(newTodo)
continue
}
newData.push(item)
}
return newData
}, false)
(Here's the modified version of the components/Todos.js file.)
Here's what we are doing in this code:
- Fetch the newly added todo item
- Replace it with the fake item in the cache
- Here we don't re-fetch data with the last mutate call
Now we are using a callback function to replace data. Previously, we directly pass a data array like this:
mutate('/api/todos', [...data, fakeItem], false)
Q: What's the reason for that?
authenticating...