Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Redux passing dispatch into the return function of an action?

Tags:

reactjs

redux

Complete beginner as far as Redux+React (and ES6) goes so bear with me - I've got all the plumbing set up and all my states update as they should, but I'm still a little confused. Following along with a tutorial, one of the Redux actions starts off with:

export function getApiData(){
       return(dispatch) => {return(dispatch) => { -some other actions here- }
}

This function fetches data from an API, so it also dispatches a getApiDataRequested and GetApiData success action, but the above does not make sense to me. Now I know that dispatches signal an intent to update the Redux state, but why is dispatch passed as parameter in the return function?

Cheers!

like image 895
Make-HCI Avatar asked Sep 12 '25 21:09

Make-HCI


1 Answers

It's because it's an example for asynchronous actions using Redux-thunk. If you look at this middleware it checks if your action is a function and if it is, it will pass dispatch to your returned function. You cannot just call an action in redux, you always have to dispatch it, so you should use dispatch object to call your action.

  function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

https://github.com/gaearon/redux-thunk

like image 185
MistyK Avatar answered Sep 14 '25 11:09

MistyK