I have a social media website where users can like/dislike posts. I have a reducer for the user and the posts. My group mate implemented the like/dislike feature as follows: whenever the user likes a post, the client calls my API with ENDPOINT 'posts/:id/like', which will increment the like count for the post in the Post Database and add the post to the user's liked posts array in the User Database. The API will return a response that contains the updated user and post, which will result in the following actions.
dispatch({
type: LIKE_POST_SUCCESS,
payload: res.payload.post
})
dispatch({
type: UPDATE_USER_SUCCESS,
payload: res.payload.user
})
And the following reducers
case LIKE_POST_SUCCESS:
return {
...state,
...action.payload
}
case UPDATE_USER_SUCCESS:
return {
...state,
...action.payload
}
This approach works, but I feel his approach seems hackish in that
Would the correct approach be
As per your question, What needs to be done is basically when the user likes a post, the Post Database should be updated first, and only after its successful response, you must update the User's Database. So, the approach that you mentioned seems to be the correct one to be followed.
Yes I agree with your approach, and yes his approach is hackish.
IMO, if the POST failed, he keep dispatch to store. Which would result in wrong data.
Or If the backend api return 201 status code but has bug for example user not updated on backend but on frontend you assume the user updated. Hence it would result wrong data in Frontend side.