Home > OS >  how to make a dispatch wait for the first dispatch to run
how to make a dispatch wait for the first dispatch to run

Time:01-27

i have 2 dispatch inside the useEffect, is there a way i can make the bottom dispatch to wait for the first one to run. i need to get the post._id from the first to pass to the second. please doesn't anyone have an idea on how to solve this?

useEffect(() => {
  dispatch(getPost(params.slug));
  dispatch(listComment(post._id));
}, [dispatch]);


// getPost action

export const getPost = (slug) => async(dispatch) => {
  try {
    dispatch({
      type: types.POST_REQUEST
    });

    const {
      data
    } = await axios.get(`http://localhost:8080/api/posts/${slug}`);

    dispatch({
      type: types.POST_SUCCESS,
      payload: data,
    });
  } catch (err) {
    dispatch({
      type: types.POST_FAIL,
      payload: err.response && err.response.data.message ?
        err.response.data.message :
        err.message,
    });
  }
};

CodePudding user response:

You can introduce a loading state for Post, and use that in another useEffect to achieve that

useEffect(() => {
    dispatch(getPost(params.slug));
  }, [dispatch]);

  useEffect(() => {
      if(!post.loading) {
        dispatch(listComment(post._id));
      }
  }, [dispatch, post.loading]);

CodePudding user response:

It's possible to coordinate this by observing loading flags with useEffect, but a simpler solution in my opinion is to extend the thunk to dispatch another action after the response for the post is available:

// actions:
export const listComments = (postId) => async (dispatch) => {
  /* thunk that fetches comments on a post */
}

// Fetch post for slug, optionally with comments.
export const getPost = (slug, withComments = false) => async(dispatch) => {
  dispatch({ type: types.POST_REQUEST });
  try {
    const { data } = await axios.get(`http://localhost:8080/api/posts/${slug}`);
    dispatch({ type: types.POST_SUCCESS, payload: data });
    if (withComments) {
      dispatch(listComments(data.id));
    }
  } catch (err) {
    const payload = err.response && err.response.data.message ?
      err.response.data.message : err.message;
    dispatch({ type: types.POST_FAIL, payload });
  }
};

// In the component:
dispatch(getPost(slug, true));

CodePudding user response:

you can try with below snippet, also will this post.id get after first dipatch or it will be present?

useEffect(() => {
    dispatch(getPost(params.slug));

     if(post._id){
       dispatch(listComment(post._id));
     }
  }, [dispatch]);

CodePudding user response:

If you fetch some data using function getPost(params), that mean you have some promise, try to use:

dispatch(getPost(params.slug).then(() => {
  dispatch(listComment(post._id))
}));

  •  Tags:  
  • Related