Search code examples
javascriptreactjsreduxreact-redux

Dispatch action from actionCreator


I studied the react redux example (shopping cart) and saw this implementation of action addToCart.

The question is, where do the dispatch and getState arguments come from?

export const addToCart = productId => (dispatch, getState) => {
  if (getState().products.byId[productId].inventory > 0) {
    dispatch(addToCartUnsafe(productId))
  }
}

I tried to copy it in my example, but I can't get it to work.

PS: i can make this with mapDispatchToProps in my example


Solution

  • They come from the thunk middleware. It allows redux action creators to not only return simple objects (with a type property), but also async functions. The middleware calls these async functions and passes dispatch and getState as arguments. Which in turn allows you to dispatch multiple other actions, look at the current state, and generally have precise control over async flow. Thunk is just one of many middlewares that support async stuff within redux actions.