Redux Q - about dispatch in async return statement

Hi there! I have passing code, and I feel like I understand the purpose of this challenge. It is to show that you can dispatch an action when you send an async request, and then dispatch some other action when you get the response, including the data which could then be sent along with that action to the store to update the state.

What I don’t understand is the meaning of the “dispatch” method being returned in the handleAsync method. It looks like the meaning should be something like this.

store.dispatch(handleAsync())
//returns first the requestingData action, 
//then after 2.5s returns the receivedData action along with the data.

How, as written, does the handleAsync function get executed in this context? Because if it returns a function like someFunction( ){ } wouldn’t that function just be returned but not called? Wouldn’t it have to be have to have a chained call (??not sure of the terminology for this??), like store.dispatch( handleAsync( )( ) ) in order for the returned anonymous function (the one passing dispatch) to be called? Or am I missing something?

Some clarity would be appreciated. Thanks! :slight_smile:

Your code so far


const REQUESTING_DATA = 'REQUESTING_DATA'
const RECEIVED_DATA = 'RECEIVED_DATA'

const requestingData = () => { return {type: REQUESTING_DATA} }
const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} }

const handleAsync = () => {
return function(dispatch) {
  // dispatch request action here
    dispatch(requestingData());

  setTimeout(function() {
    let data = {
      users: ['Jeff', 'William', 'Alice']
    }
    // dispatch received data action here
   dispatch(receivedData(data));

  }, 2500);
}
};

const defaultState = {
fetching: false,
users: []
};

const asyncDataReducer = (state = defaultState, action) => {
switch(action.type) {
  case REQUESTING_DATA:
    return {
      fetching: true,
      users: []
    }
  case RECEIVED_DATA:
    return {
      fetching: false,
      users: action.users
    }
  default:
    return state;
}
};

const store = Redux.createStore(
asyncDataReducer,
Redux.applyMiddleware(ReduxThunk.default)
);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.

Challenge: Use Middleware to Handle Asynchronous Actions

Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/redux/use-middleware-to-handle-asynchronous-actions