[已解决]Redux: Use Middleware to Handle Asynchronous Actions


#1

Tell us what’s happening:

问题:无法通过测试的最后一项:

如果要 dispatch handleAsync 应先 dispatch 数据请求的 action,然后在收到请求结果后再 dispatch 接收的数据 action。

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 请求的 action
    dispatch(requestingData);

    setTimeout(function() {
      let data = {
        users: ['Jeff', 'William', 'Alice']
      }
      // 在这里 dispatch 接收到的数据 action
      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/73.0.3683.86 Safari/537.36.

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