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 .....