Challenges

SWR

Add Optimistic UI support

Now we are going to add the optimistic UI support.

For that replace the addToDo function in the components/Todos.js with the following content:

const addTodo = async (todoName) => {
    // Add fake item and re-render the UI
    const fakeItem = {
        id: Math.random(),
        name: todoName,
        clientOnly: true
    }
    mutate('/api/todos', [...data, fakeItem], false)
    setListKey(Math.random())

    // Add the todo Item
    const addRes = await fetch('/api/todo', {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({name: todoName})
    })

    if (!addRes.ok) {
        const {error} = await addRes.json()
        throw new Error(error.message);
    }

    // Refetch the list
    mutate('/api/todos')
}

(Here's the modified version of the components/Todos.js file.)

In this version, we do three main things:

  1. First, we push a fake item to the cache, and it will render the UI
  2. Then we invoke the API, which adds the todo item.
  3. Finally, we will call mutate('api/todos') to invalidate the cache and fetch data again

Now, let's have a look at the first mutate function:

const fakeItem = {
    id: Math.random(),
    name: todoName,
    clientOnly: true
}

mutate('/api/todos', [...data, fakeItem], false)
  • With the second argument, we replace the existing cache for the key api/todos
  • With the third argument as false, we ask SWR to stop invalidating and fetch data

We also have this clientOnly: true flag in the fake todo item, which we can use to identify the fake item from the real. Then when we can add a different CSS style to this fake item. You can inspect the components/TodoList.js on how we are doing it.

Okay, now it's time for a question:

Try to add a bunch of todo items quickly. You can do that by typing something and pressing the Enter key.
(Do not add empty items as it will throw an error)

Q: How do you describe your experience?
authenticating...