I have a React app with Redux store. I'm using two pages - index page and edit post page. When user goes to edit page it loads the post content from the server and setting it in Redux store. Code looks like this:
const EditPost = props => {
const { postId } = useParams();
const { isLoading, error, post } = useSelector(state => state.post);
const dispatch = useDispatch();
useEffect(
() => {
if (postId) dispatch(getPost(postId));
},
[dispatch, postId]
);
if (isLoading) {
return <div>Post is loading...</div>
}
if (error) {
return <div>Error: {error}</div>
}
return (
<div>Post content here...</div>
)
}
The problem is when user navigate to index page the post in Redux is already setted and user sees the last edited post instead default index post. The code of index page is:
const Index = props => {
const { isLoading, error, post } = useSelector(state => state.post);
const dispatch = useDispatch();
const postId = defaultPostId;
useEffect(
() => {
dispatch(getPost(postId));
},
[dispatch, postId]
);
if (isLoading) {
return <div>Post is Loading...</div>
}
if (error) {
return <div>Error: {error}</div>
}
return (
<div>Default index post here...</div>
)
}
My desired behavior has to be like if user goes to index page after edit post it should see the loading and then the default post content. But the current situation is user sees the last edited post, then loading process and then it shows default post. Obviously because Redux contains last post data in store.
So the question is: How and when to set post to default state? I assume it's related to lifecycles.
P.S getPost action code looks like this:
export const getPost = postId => {
return async (dispatch, getState) => {
try {
dispatch(isPostLoading(true));
const { data: post } = await req.get(`/post/${postId}`);
dispatch(setPost(post));
dispatch(setPostError(null));
} catch (error) {
setPostError(error.message);
}
dispatch(isPostLoading(false));
}
}