0

I'm struggling to get a mini project of mine to optimistically render when a user tries to delete a comment of their own. Currently the array of comments is coming down on props from a parent component, and before that is from the backend. I'm trying to get it so the comment deletes instantly, rather than waiting for a successful 204 code from the backend. I'm having issues with it and I'm not sure why. I'll post a code snippet below for the relevant information.

Upon the user clicking, I'm trying to filter the current comments, to remove the relevant comment by comment id, and then set the state of allComments using this new "filtered" array. Any help would be great.

The filtered array seems to render on the page for a split second and then reverts back to the non deleted array of comments, and I'm not sure why. I've tried wrapping it in a useeffect with the comments as a dependency.

Hopefully that makes sense, any help is appreciated!

const handleDeleteClick = (commentId) => { 

  if (loggedInUser === comment.author) { 

    const filtered =  currComments.filter((commentToDelete) => { 
      return commentToDelete.comment_id !== commentId 
    }); 

    setAllComments(filtered);
 
    deleteComment(comment.comment_id).then((statusCode) => { 
      if (statusCode === 204) { 
        alert("succesfully deleted comment");
      } 
    }).catch((err) => { 
      alert("Something went wrong, please try again.") 
    }); 
  } else .....
Buggies
  • 383
  • 1
  • 7
  • This is not the best way to do that what happens when you remove data from your side and in API failed then data not deleted from the server you show that data is deleted. – Meet Majevadiya Jul 13 '22 at 06:06
  • I will add some error handling incase there is an issue with deleting the data, it will reverse the optimistic approach. I just want to learn how to do it. – Houdini23 Jul 13 '22 at 06:12

1 Answers1

0

Try this first: comment out your backend API call and test whether the front-end code works or not.

const handleDeleteClick = (commentId) => {

    if (loggedInUser === comment.author) {

        const filtered = currComments.filter(commentToDelete =>
                           commentToDelete.comment_id !== commentId);
        setAllComments([...filtered);

    }
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Meet Majevadiya
  • 355
  • 2
  • 8
  • Hi, thanks for the reply. The comment deletes for a split second, and then reappears. When I simulate it through a low speed mobile, it becomes more noticeable, but the deleted comment always reappears. This still happens when the backend api call is commented out. – Houdini23 Jul 13 '22 at 07:29