Search code examples
reactjsstatecomments

React doesn't update comments AND comment amount even if i update state , i have to refresh the page to see new comments and amount of comments


handleCreateComment gets called from my child component called Comments but the new comment doesn't render even if i update the state.

 //create Comment
 handleCreateComment = async (Comment, foodId, UserId) => {
   createComment(Comment, foodId, UserId).then((res) => {
    const newComment = res.data;
    const newComments = [...this.state.Comments, { newComment }];
    this.setState({ Comments: newComments });
   });
 };

commentAmount gets called in the Posts component and shows the amount of comments for that specific post, i would like to call this function after state changes aswell so it shows the correct amount of comments.

commentAmount(food) {
  const comments = this.state.Comments.filter(
   (comment) => food === comment.foodId
  );
  return comments.length;
 }

In my jsx i for the Posts i call the commentAmount function that shows the amount of comments like this. I also render my Comments component in the posts component.

// i want this function to get called everytime a user creates a comment so i can see the 
//correct  number of comments for that post 
  <u> {this.commentAmount(food.id)}</u>;

         <Comments
            user={this.props.user}
            username={username}
            admin={admin}
            foodId={food.id}
            UserId={id}
            Comments={this.state.Comments}
            handleDeleteComment={this.handleDeleteComment}
            handleCreateComment={this.handleCreateComment}
             />

Here is my Comments component

This is how i render my Comments in the Comments component, All comments are in the same array and are not included in the posts from the backend so i have to filter them.

    function Comments({
     foodId,
     UserId,
     Comments,
     admin,
     handleDeleteComment,
     user,
     handleCreateComment,
     }) {
     return (

      {Comments.filter((comments) => {
          return comments.foodId === foodId;
         }).map((comment) => {
         return (
          //Some jsx for displaying the comments
          })}
         );
       }
 export default Comments;

Solution

  • I think your problem might be here:

    const newComments = [...this.state.Comments, { newComment }];
    

    Try changing it to:

    const newComments = [...this.state.Comments, newComment];
    

    Or simpler:

    const newComments = [...this.state.Comments, res.data];
    

    Hope this helps!