I am having trouble understanding how this Redux code even works. I understand what asynchronous is, but I can’t understand how the code below even runs.
requestingData
and receivedData
are creators that return actions. Is handleAsync
a creator or just a normal function that runs?
When the code runs, I get a console statement for the value of the store’s state:
{ fetching: false, users: [] }
handleAsync()
doesn’t even run in the code, and I have no idea how to run it. I tried calling it with handleAsync()
, but still the state is not updated.
store.dispatch(creator)
is how it is normally done, but in this case it is done totally different. I don’t understand where the value of dispatch is coming from. Is it from the middleware? Is it the same as store.dispatch()
, but tells the redux it is async?
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(requestingData());
setTimeout(function() {
let data = {users: ["Jeff", "William", "Alice"]};
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)
);
handleAsync()
console.log(store.getState())
Challenge: Use Middleware to Handle Asynchronous Actions
Link to the challenge: