Challenges

Add Optimistic UI Support

Invoke the API

Now we need to invoke the API to create the actual comment. For that, open the components/Comments.js and add the following function inside the Comments React components:

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()
}

As you can see, here we invoke the API to add the comment and invoke mutate() at the end to refetch comments from the API.

Then invoke this function inside handleAddComment function like this:

const handleAddComment = async (content) => {
    const fakeComment = {
        id: Math.random(),
        userId: session.user.id,
        name: session.user.profile.name,
        avatar: session.user.profile.avatar,
        content,
        createdAt: Date.now(),
        clientOnly: true
    }

    mutate([...comments, fakeComment], false)

    createComment(fakeComment)
}

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

Now try to add a comment. You will get an experience like this.


Inside handleAddComment function we invoked the createComment function without await. Try to add await infront of it like this:

await createComment(fakeComment)

Then add a comment.

Q: What was your experience?
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: