Challenges

SWR

Add a Todo Item

Now it's time to add a todo item. We are working on the components/Todos.js file.

First import mutate from SWR like this:

import useSWR, {mutate} from 'swr'

Then replace the addTodo function with the following:

const addTodo = async (todoName) => {
    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);
    }

    await mutate('/api/todos')

    setListKey(Math.random())
}

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

In this code, we make an HTTP POST request to add a todo item. Then we call the following mutate function.

await mutate('/api/todos')

In this case, what mutate does is pretty simple. It will refetch data related to the cache key(api/todos) and re-render the UI.

Okay, now it's time for a question:

Now try to add a couple of todo items.
(You can reset items on the todo list by modifying any file in this app.)

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