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)
 })
}};
2
  • Does this answer your question? chaining async method calls - javascript Commented Apr 5, 2020 at 7:38
  • No I'm not looking for a promise based solution Commented Apr 5, 2020 at 7:45

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.