Why do I have to refresh the page when I delete a post? MERN stack

Solution 1:

I believe the issue is that you are not fetching the posts after delete is successful.

Try this inside the HomePage component:

...
const [isDeleting, setIsDeleting] = useState(false);
const { loading: loadingDelete, error: deleteError } = deletePost;

useEffect(() => {
    dispatch(getPosts());
}, [dispatch]);

useEffect(() => {
    if (!deleteError && isDeleting && !loadingDelete) {
        dispatch(getPosts());
    }
    setIsDeleting(loadingDelete);        
}, [dispatch, deleteError, isDeleting, loadingDelete]);
...

Another method is to use "filtering", but you have to update your reducer as such:

export const deletePostReducer = (state = {}, action) => {
  switch (action.type) {
    case DELETE_POST_BEGIN:
      return { loading: true };
    case DELETE_POST_SUCCESS:
      return { loading: false, data: action.payload}; // <-- this was changed
    case DELETE_POST_FAIL:
      return { loading: false, error: action.payload.msg };
    default:
      return state;
  }
};

Now in your HomePage component, you will do something like this when rendering:

...
const { loading: loadingDelete, data: deletedPost } = deletePost;
...
useEffect(() => {
  dispatch(getPosts());
  if (deletedPost) {
    console.log(deletedPost);
  }
}, [dispatch, deletedPost]);
  
return (
   ...
   <Row>
     {posts.filter(post => post._id !== deletedPost?._id).map(post => (
        <Col lg={4} key={post._id} className='mb-3'>
           <Post post={post} />
        </Col>
     ))}
   </Row>
)