How should I update the state after a comment is deleted from the db.
This is my delete function but I cannot seem to figure out what have to be the contents of dispatch:
const onCommentDelete = async (id) => {
const commentId = id;
const response = await commentService.deleteComment(commentId);
dispatch({
type: 'COMMENT_DELETE',
payload: commentId,
});
}
I am also not sure how to remove this specific comment from the state in the actual Reducer? I am trying something like this, but still cannot get it to work:
switch (action.type) {
case 'COMMENT_DELETE':
return {
...state,
comments: state.comments.filter((comment, commentId)
=> commentId !== action.payload)
}
//...
}
The comments in the DB look like this:
[
{
"_ownerId": "35c62d76-8152-4626-8712-eeb96381bea8",
"blogId": "0977d18f-fa62-473b-9ee0-16a5d8910d14",
"comment": "First comment",
"_createdOn": 1680544822712,
"_id": "2ce82346-19b9-471c-9ae2-f6efd0b2891c"
},
//...
]
I did read some previous threads but cannot understand how to use the information from them…
2
Answers
You have three options:
update your endpoint and make it return the new comments list so you can pass it as
action.payload
tostate.comments
directly.you make another API call to get all the comment after you delete one of them. (not recommanded)
update your state based on the returned id as you are trying to do:
The filter method takes two parameters, the first is the element the second is the index, so your code does not work or let’s say returns an empty array because the function cannot find in any of the itterations an index equal to
action.payload
you have to filter based on thecomment.id
instead.Learn more about Array.prototype.filter().
The difference between the first and the third method is that the first will ensure that your state and your database are always synchronized, however in the third you try to make them synchronized manually, this can be a good solution if the data is really large otherwise it is better to opt for the first approach.
A simple step you can do is do a refetch every time you dispatch this action.
you can achieve this by making like a boolean flag (maybe) called isSuccess and this boolean flag will be watched by the deps array in useEffect and whenever it’s changing the refetch callback will be called.
tip: make sure that you only fire the callback when it’s true