Tell us what’s happening:
I did what the challenge asked me to do. The test passed. I still don’t understand this concept. Trying to look this up YouTube or reading about it only makes things more confusing.
Can somebody tell me if I’m understanding this wrong:
If I know I need to request data from, say, a server, and I know this is going to take time, then I don’t want to immediately update the Redux store because this will cause an error (updating with no data).
So I set up a thunk, get the middleware set up etc.
Now, instead of directly dispatching the store to update data like before, I break it up into 2 separate dispatches:
- dispatch telling store I got data incoming, so wait for it
- dispatch telling store I got the data, so pass the data to the reducer so it could do its thing
Therefore, I wouldn’t call requestingData() anywhere in the code except inside the thunk? Instead, I would call the thunk like so:
handleAsync();
And this thunk will automatically send out the first dispatch requestingData().
The thunk will then wait until it gets a response in the form of a dispatch, which is entered as an argument in the function returned by the thunk? As in:
handleAsynch()(incoming dispatch); --> this looks like a curried function, so it takes in a dispatch as an argument, right?
Then the thunk will send out the final dispatch receivedData()?
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
store.dispatch(requestingData());
setTimeout(function() {
let data = {
users: ['Jeff', 'William', 'Alice']
}
// dispatch received data action here
store.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/75.0.3770.142 Safari/537.36
.
Link to the challenge: