Redux: Using Middleware

Hey, how are you all?
I only have a simple question: how do I dispatch the receivedData() action into this handleAsync() action creator so that I can see the updating of the state after 2500ms?

As you can see at the end, I tried:

console.log(store.getState());
store.dispatch(handleAsync());
console.log(store.getState());

but it only returns:

{ fetching: false, users: [] }
{ fetching: true, users: [] }

and I expected:

{ fetching: false, users: [] }
{ fetching: false, users: ['Jeff', 'William', 'Alice'] }

Here’s the code:

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)
);
console.log(store.getState());
store.dispatch(handleAsync());
console.log(store.getState());

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.