Search code examples
reactjsruby-on-railsreact-router-dom

I am having trouble getting my comments to post


enter image description hereI am having trouble getting my comments to post. Can someone look at my codes and give me some feedback?

Whenever I post a comment, the screen flashes but nothing posts. I tested the back-end functions on Postman and everything there works fine so I'm assuming something isn't working properly in the front end.

I've tried everything I can. Fairly new to coding and not sure what to try next.

useEffect(() => {
    if(!loggedIn) {
        navigate.push('/login')
    }
    return () => {
        setErrors([])
    }
}, [loggedIn, setContent, navigate, setErrors])

const handleSubmit = (e) => {
    e.preventDefaul();
    const newContent = {
        content: content,
        blog_id: blog.id
    }
    fetch('/comments', {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(newContent)
    })
    .then(resp => resp.json())
    .then(data => {
        if(data.errors) {
            setErrors(data.errors)
        } else {
            addComment(data)
        }
    });
}

Solution

  • you misstyped preventDefault just below the function declaration of handleSubmit you wrote e.preventDefaul(). While I cannot see the rest of your component what I assume is happening, is that the forms submits which triggers a reload and stops the promise from sending. Fixing this typo will probably fix your problem.