Search code examples
reactjsreduxes6-promise

(React/Redux) Dispatching 2 actions after a resolved promise


I got a promise, which after it resolves I want to dispatch two different actions to two different reducers.

This code breaks :

 axios
    .post('http://localhost:4000/api/users/saveUser', user, config)
    .then((res) =>
      dispatch({
        type: ADD_USER,
        payload: res.data,
      })
    )
    .then((res) =>
      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data,
      })
    )
    .catch((err) =>
      dispatch(returnErrors(err.response.data, err.response.status))
    )

How should I do it right?


Solution

  • Just dispatch both of them in the same then block.

    axios
      .post('http://localhost:4000/api/users/saveUser', user, config)
      .then((res) => {
        dispatch({
          type: ADD_USER,
          payload: res.data,
        });
        dispatch({
          type: REGISTER_SUCCESS,
          payload: res.data,
        });
      })
      .catch((err) =>
        dispatch(returnErrors(err.response.data, err.response.status))
      );
    

    Otherwise at the end of the first then block, you'd need to return res so that the second then block has access to res.

    axios
      .post('http://localhost:4000/api/users/saveUser', user, config)
      .then((res) => {
        dispatch({
          type: ADD_USER,
          payload: res.data,
        });
        return res;
      })
      .then((res) =>
        dispatch({
          type: REGISTER_SUCCESS,
          payload: res.data,
        })
      )
      .catch((err) =>
        dispatch(returnErrors(err.response.data, err.response.status))
      );