Challenges

Add Optimistic UI Support

Avoid Refetching

Have a look at the createComment function we added in the previous step:

const createComment = async (fakeComment) => {
    const fetchRes = await fetch(`/api/comments?slug=${slug}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ content: fakeComment.content })
    })

    if (!fetchRes.ok) {
        throw new Error(await fetchRes.text())
    }

    const addedComment = await fetchRes.json()
    mutate()
}

Here we call the mutate() at the end. So, it will refetch data from the server. This will raise two issues:

  • It will do an unnecessary data refetch because the "create comment API" will return the actual comment we added
  • If we add multiple comments at the same time, the UI will be unstable

Let's fix this:

Replace the above mutate() function call inside components/Comments.js with the following:

mutate((currentComments) => {
    const newComments = []
    for (const c of currentComments) {
        if (c.id === fakeComment.id) {
            newComments.push(addedComment)
        } else {
            newComments.push(c)
        }
    }

    return newComments
}, false)

(Here's the final version of the file after all these changes.)

Try to add a comment. You won't see any difference from the previous step. That's expected because we added an improvement, which is hard to visualize.

Here we pass a callback function as the first argument to the mutate function. But earlier, we passed an array.

Q: Why was that?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: