0

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)
 })
}};
  • Does this answer your question? [chaining async method calls - javascript](https://stackoverflow.com/questions/39028882/chaining-async-method-calls-javascript) – Utsav Patel Apr 05 '20 at 07:38
  • No I'm not looking for a promise based solution –  Apr 05 '20 at 07:45

1 Answers1

0

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
}
Barun Patro
  • 860
  • 4
  • 13