Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling one async function inside another in redux-thunk

I'm building a react app and use redux-thunk for async operations. I have two functions getActivities() and createActivity() and I want to call the former after successful calling the latter. But if I put getActivities() inside then block of createActivity() it simply isn't get called (which is proved by not seeing console.log() which I put in getActivities()). Here are both functions:

export const getActivities = () => dispatch => {
console.log('again');
return axios.get(ENV.stravaAPI.athleteActivitiesBaseEndPoint, autHeaders)
    .then(resp => {
        dispatch({type: actions.GET_ACTIVITIES, activities: resp.data})
    })
    .catch(err => {
        if(window.DEBUG)console.log(err);
    })
};

export const createActivity = data => dispatch => {

dispatch(setLoadingElement('activityForm'));
return axios.post(URL, null, autHeaders)
    .then(resp => {
        if (resp.status === 201) {
            dispatch(emptyModal());
        }
        // I WANT TO CALL getActivities() HERE
        dispatch(unsetLoadingElement('activityForm'));
    })
    .catch(err => {
        if(window.DEBUG) console.log(err.response.data.errors);
        dispatch(unsetLoadingElement('activityForm'));
    });
};

How can I call one inside another?

like image 622
turisap Avatar asked Jan 20 '18 17:01

turisap


1 Answers

In order to call another action from inside one action creator you just need to just dispatch the action like dispatch(getActivities())

export const createActivity = data => dispatch => {

    dispatch(setLoadingElement('activityForm'));
    return axios.post(URL, null, autHeaders)
        .then(resp => {
            if (resp.status === 201) {
                dispatch(emptyModal());
            }
            dispatch(getActivities());
            dispatch(unsetLoadingElement('activityForm'));
        })
        .catch(err => {
            if(window.DEBUG) console.log(err.response.data.errors);
            dispatch(unsetLoadingElement('activityForm'));
        });
 };
like image 147
Shubham Khatri Avatar answered Sep 30 '22 22:09

Shubham Khatri