Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

enter image description here

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading