1

I am having a little difficulty understanding how Redux-Thunk (or other middleware) execute async actions. From below example, I can see that when onOrder is called (maybe via a click event), it will dispatch the action created by purchaseBurger. purchaseBurger in turn return a function that will dispatch an action indicating purchase started, followed by an http request. My confusion is: When does that function returned by purchaseBurger actually gets called and executed? How does it get called too?

ContactData.js
const mapDispatchToProps = dispatch => {
        return {
            onOrder: (orderData) => dispatch(actions.purchaseBurger(orderData))
        }
    }

orders.js
export const purchaseBurgerStart = (orderData) => {
        return {
            type: actionTypes.PURCHASE_BURGER_START
       }
    }

export const purchaseBurger = (orderData) => {
    return dispatch => {
        dispatch(purchaseBurgerStart());
        axios.post('/orders.json', orderData)
        .then(response => {

        })
        .catch(error => {
            this.setState({ loading: false });
        })
    }
}
coffeeak
  • 2,980
  • 7
  • 44
  • 87

1 Answers1

3

If you take a look at the source of redux-thunk you will see that when you dispatch an action it checks to see if the action is a function, and if it is it will invoke the function passing in dispatch, getState, extraArgument as arguments.

So when you call dispatch(purchaseBurger()) it will dispatch the returned function from purchaseBurger as an action, the middleware will then check the type and see that it is a function and will call it with dispatch as the first argument

Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45