Thunk Middleware: how/why does action creator have access to dispatch when it's not passed in?

Advertisements

For reference, this is the origin of the below screenshots: https://github.com/gopinav/React-Redux-Tutorials/blob/master/redux-demo/asyncActions.js

Looking at the fetchUsers action creator function in the below screenshot, how is dispatch passed into this function? Not clear how the fetchUsers function has access to dispatch and can pass it into the anonymous return function within fetchUsers.

The store creation in the 2nd screenshot is where the thunkMiddleware is applied and the fetchUsers is dispatched.

>Solution :

@JLRishe answered this correctly in a comment.

fetchUsers is a function that returns an anonymous function. The anonymous function takes the dispatch function as an argument. When you call store.dispatch(fetchUsers()), note that you’re passing the return value of fetchUsers to store.dispatch. Redux then calls this anonymous function, passing it the dispatch method as an argument. The anonymous function is then invoked and can use the passed in dispatch function to dispatch additional actions.

Leave a ReplyCancel reply