Reputation: 231
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?
Upvotes: 9
Views: 4758
Reputation: 83557
getActivites()
This does sucessfully call getActivities()
. However, it returns an anonymous function which contains the console.log()
call. You ignore this returned value here.
You must dispatch the returned function in order to ensure it is called:
dispatch(getActivities())
Upvotes: 0
Reputation: 281854
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'));
});
};
Upvotes: 10