Challenges

Add Comments Support

UI to Add Comments

Now it's time to implement a UI to add comments. First of all, create a file called components/AddCommentBox.js and add the following content:

import { useState } from "react"

export default function AddCommentBox({onSubmit}) {
    const [commentText, setCommentText] = useState('')
    const [adding, setAdding] = useState(false)

    const handleAddComment = async () => {
        try {
            setAdding(true)
            await onSubmit(commentText)
            setCommentText('')
        } finally {
            setAdding(false)
        }
    }
    
    return (
        <div className="add-comment-box">
            <textarea
                value={commentText}
                onChange={(e) => setCommentText(e.target.value)}
            />
            <button
                onClick={handleAddComment}
                disabled={adding}
            >
                {adding? 'adding...': 'Add Comment'}
            </button>
        </div>
    )
}

It's a simple UI to accept a comment. Once the user clicks the "Add Comment" button, it will invoke onSubmit prop. That's where we need to implement the actual logic to add a comment.

To do that, import the above component inside components/Comments.js:

import AddCommentBox from './AddCommentBox'

Then use it just after we render all comments:

<AddCommentBox onSubmit={handleAddComment}/>

Then let's implement the handleAddComment function inside the AddCommentBox stateless React component:

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

    if (!fetchRes.ok) {
        alert(`Error: ${fetchRes.text()}`)
    }

    mutate()
}

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

Now you can add a comment right from the UI. Give it a try.

Q: What's the purpose of the `mutate()` function call?
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: