0

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.

enter image description here

enter image description here

brunshte
  • 153
  • 2
  • 9
  • 2
    The `fetchUsers` function _doesn't_ have access to `dispatch`. The middleware has access to dispatch, and it will pass `dispatch` into your function. – JLRishe Jan 15 '23 at 18:03

1 Answers1

1

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

Jimmy
  • 35,686
  • 13
  • 80
  • 98
  • just to follow up on that: in a more simple case `store.dispatch` takes an action object as an argument, while here it takes a function as an argument and then essentially passes in to that function itself (`dispatch`) as an argument of that function. Did I characterize that correctly? – brunshte Jan 15 '23 at 18:26
  • 1
    Yes, that's exactly right. Redux checks the type of object you pass to `dispatch`. If it's a function, it calls the function, passing it the reference to `dispatch`. – Jimmy Jan 15 '23 at 19:04