How to call an async action after another action was successfully dispatched?
I am learning Redux and I have some questions, about async action.(I am using thunk)
I have two action:
export const addToCart = addToCartData => dispatch => {
axios.post("/api/cart/add-to-cart", {addToCartData)
.then(res => {
dispatch({ type: ADD_TO_CART, payload: res.data });
})
.catch(err => console.log(err));
};
export const removeProduct = (userID) => dispatch => {
axios
.delete(`/api/wait-list/remove/${userID}`)
.then(res => {
dispatch({ type: REMOVE_FROM_WAITLIST, payload: res.data });
})
.catch(err => console.log(err));
};
And I want to execute removeProduct
action only after addToCart
will be successfully executed! I am trying to do third one with two of them, it looks like this:
export const addToCartAndPemoveProduct = (data) => dispatch => {
dispatch(addToCart(data)
dispatch(removeProduct(data));
But it executes removeProduct
action first, and after addToCart
....
How do I can do it right due to order? Maybe I should return a promise from first one and execute second one after it will be successfull resolve? It will be looking like this:
export const addToCart = addToCartData => dispatch => {
return axios.post("/some", {addToCartData)
.then(res => { dispatch({ type: ADD.....})
};
export const addToCartAndPemoveProduct = (data) => dispatch => {
dispatch(addToCart({ userID, productId }))
.then(data => {
dispatch(removeProduct({ userID, productName, productDescr }));
})
}
Is it ok or not?