redux thunk calling two different api requests

1.6k views Asked by At

trying to call two api's in an action. When one is complete call the other then on the last one pass it off to a reducer. Looks like my getAttending is getting called at the same time as post and not after post is completed. I'm new to redux-thunk and thought I could just call them one after another as the completed.

   export function postDeclined(id){
        let post = axios.post(blaBla.com);
        let getAttending = axios.get(attending.com);
        return (dispatch) => {
            post.then(()=>{
                getAttending.then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }
3

There are 3 answers

0
Lucas Katayama On BEST ANSWER

Try doing the api calls like this:

 export function postDeclined(id){
        return (dispatch) => {
             axios.post(blaBla.com).then(()=>{
                 axios.get(attending.com).then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

When you "declared" the calls, you were actually calling the API... so it was doing async...

2
Paul. B On

I'd add async/await to your babel config. Makes reading/debugging these things a lot easier.

export const postDeclined => (id) => async (dispatch) => {
  const post await axios.post(blaBla.com);
  const getAttending = await axios.get(attending.com);
  return dispatch({
    type: type.NOT_GOING,
    payload: getAttending.data
  });
};
0
Ivan Demchenko On

There is a very common problem with the code sample. The function does two things at once: do calls to apis and dispatch an action. Also, please note, that you can chain Promises, you don't need that intermediate callback:

 export const postDeclined = id =>
   axios.post(blaBla.com).then(axios.get(attending.com));

 export const notifyNotGoing = dispatch => promisedResult =>
   promisedResult.then(({data}) =>
     dispatch({
       type: type.NOT_GOING,
       payload: data.data
     })
   );

And then you can call your function like that:

notifyNotGoing(dispatch)(postDeclined(2))

or using composition and currying (I personally prefer Ramda)

const prog = compose(notifyNotGoing(dispatch), postDeclined)
prog(2)