Challenges

Add Comments Support

Login to Add Comments

Right now, our comments functionality has a problem.

Q: What's that?
authenticating...

Let's fix this issue.

To do this, replace the components/AddCommentBox.js with the following content:

import { useState } from "react"
import { useSession, signIn } from 'next-auth/client'

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

    const handleLogin = () => {
        signIn('github')
    }

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

Run your app and give it a try.

šŸ’” As you can see, we get the next-auth session and use it to change the UI accordingly.

šŸ™ We need your help

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