user9667412
user9667412

Reputation:

How to dispatch two async redux action one after another?

In my componentDidMount I am dispatching two action creators i.e thunks both called one after another. The result fetched in the api call of first dispatch is to be used as the parameter in the api call of second dispatch. How I can make it so that my second dispatch call always gets the updated result value from the first api call. Also, I can't call my second dispatch inside the first action creator as they both need to be separate for reusability. Apologies if the question is already asked I'm just looking for a perfect solution for my use case.

componentDidMount() {
  const { setLeadTypesAsync ,setRadarLeadsAsync } = this.props;
  setLeadTypesAsync(); //first dispatch
  setRadarLeadsAsync();  //second dispatch
}

//First dispatch call
export const setLeadTypesAsync = () => {
 return (dispatch) => {
 dispatch(setLeadTypesStart());
 fetchLeadTypes()  //Api service
  .then(({ data: { message, types } }) => {
    if(types) {
      dispatch(setLeadTypesSuccess(types)); //Setting a state called leadTypes
    }
    else {
      dispatch(setLeadTypesError(message));
    }
 })
}};

//Second dispatch call
export const setRadarLeadsAsync = () => {
 return (dispatch, getState) => {
 dispatch(setRadarLeadsStart());
 const { leadTypes } = getState().leads
 console.log(leadTypes);    //Getting the initial value [] instead of updated value
 fetchRadarLeads(leadTypes).then(data => {   //Api service
   console.log(data)
 })
}};

Upvotes: 0

Views: 1065

Answers (1)

Barun Patro
Barun Patro

Reputation: 860

this is exactly the kind of situation where async/await comes into play.. Like this..

async componentDidMount() {
  const { setLeadTypesAsync ,setRadarLeadsAsync } = this.props;
  const res = await setLeadTypesAsync(); //first dispatch
  setRadarLeadsAsync(res);  //second dispatch
}

Upvotes: 0

Related Questions