skip to Main Content

I have a React app where I’m trying to create a POST request using Axios, but it doesn’t seem to work. The strange part is I have checked my backend route and tested it with Nodemon. everything is working fine there but I don’t understand why the route is not working in the front end

Frontend – This is where I tested my endpoint in nodemone and it worked just fine.

enter image description here

API is working fine too.

enter image description here

and this is my code in the front end

enter image description here

The error I’m getting:

enter image description here

2

Answers


  1. I have read your code and I found some issues. You can improve it by some steps:

    1- Defined an async function fetchComments inside useEffect and called it immediately.

    2- Used currentUser passed as a prop to set the username in commentToSend.

    3- When a new comment is posted, it prepends the new comment to the existing comments.

    It would be better to use ES6, for example arrow function.
    Here’s the correct code

    import React, { useState, useEffect } from "react";
    import CommentList from "./CommentList";
    import fetchApi from "./fetchApi";
    
    function CommentAdder({ article_id, currentUser }) {
      const [comments, setComments] = useState([]);
      const [newComment, setNewComment] = useState("");
    
      useEffect(() => {
        const fetchComments = async () => {
          try {
            const res = await fetchApi().get(`/api/articles/${article_id}/comments`);
            setComments(res.data.comments);
          } catch (error) {
            console.error(error);
          }
        };
    
        fetchComments();
      }, [article_id]);
    
      const postComment = async (newCommentData) => {
        try {
          const res = await fetchApi().post(`/api/articles/${article_id}/comments`, newCommentData);
          setComments([res.data, ...comments]);
        } catch (error) {
          console.error(error);
        }
      };
    
      const handleOnSubmit = async (e) => {
        e.preventDefault();
        const commentToSend = {
          username: currentUser,
          body: newComment,
        };
        await postComment(commentToSend);
      };
    
      return (
        <div>
          <form onSubmit={handleOnSubmit}>
            <textarea value={newComment} onChange={(e) => setNewComment(e.target.value)} />
            <button type="submit">Add Comment</button>
          </form>
          <CommentList comments={comments} />
        </div>
      );
    }
    
    export default CommentAdder;
    

    If I were you, I would have used Redux-toolkit also to presist data or some other tools like react-query to cache request for better performance.

    Try to use the console log to see the EndPoint URL

    const postComment = async (newCommentData) => {
      try {
        console.log(`Posting to /api/articles/${article_id}/comments with data:`, newCommentData);
        const res = await fetchApi().post(`/api/articles/${article_id}/comments`, newCommentData);
        setComments([res.data, ...comments]);
      } catch (error) {
        console.error('Error posting comment:', error);
      }
    };
    
    Login or Signup to reply.
  2. When testing the same POST request on my side (username: "butter_bridge"), the response I got was 404: "No user found for article_id"

    So, my bet is that the issue rather lies with the API – the given username and the article are not compatible somehow 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search