Blankman
Blankman

Reputation: 267280

Chaining redux thunk actions together

How could I modify toggleShowUsers to first call fetchUser and then dispatch with type Constants.ShowUsers after?

toggleShowUsers: () => {
  return dispatch => {
    dispatch({
      type: Constants.ShowUsers,
    });
  }
},
fetchUser: (userId) => {
  return dispatch => {    
    let url = ....
    axios.get(url)
      .then(function(resp) {
        dispatch({
          type: Constants.fetchUser,
          users: resp.data.users,
        });
      });
  };
},

So in my react component I am doing this in the

componentDidMount() {
    const { dispatch } = this.props;

    dispatch(Actions.toggleShowUsers());
}

I want to first call fetchUser and then toggleShowUsers.

Upvotes: 0

Views: 32

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

There are a few ways to achieve this. One approach is to do the following:

const toggleShowUsers = () => {
  return dispatch => {

    // [UPDATE]
    // Once the toggle is complete, do fetch 
    // request. Not sure how you plan to aquire
    // the id, so am substituting value 1 here
    fetchUser(1)(dispatch).then(() => {

        // [UPDATE] 
        // In promise handler, dispatch ShowUsers
        // when fetchUser has completed
        dispatch({
          type: Constants.ShowUsers,
        });
    });
  }
}

const fetchUser = (userId) => {
  return dispatch => {    
    let url = ....

    // [UPDATE] 
    // Return promise from axios.get 
    return axios.get(url)
      .then(function(resp) {
        dispatch({
          type: Constants.fetchUser,
          users: resp.data.users,
        });
      });
  };
}

export default { toggleShowUsers, fetchUser }

Upvotes: 1

Related Questions