Tell us what’s happening:
I’ve completed the challenge, and now I’m playing around with dispatch(), getState() to map out its behavior and try to understand what they’re doing.
As you can see in the code, I’ve modified the state returned by the reducer so that each time it returns a state, there’s a key: value pair in it that allows me to log what the Redux store is spitting out. For example, {authenticated: true, a: 123}.
I send out multiple dispatches to the store. I use the getState() on the store and log the outcome. It seems getState() only returns the most recent state that the store processed. My question is: how is this useful?
If the reducer, in principle, should not directly modify the app’s state, instead it spits out a copy of a part of its state, then how does the global state of the app get updated? The Redux store doesn’t keep a copy of everything the reducer churns out. All the “state” objects get lost except for the most recent one. So if multiple users login and logout, all that information is being lost. How is the Redux store a “store” of anything?
Does this get answered in the Redux-React section?
Thanks.
Your code so far
const defaultState = {
authenticated: false
};
const authReducer = (state = defaultState, action) => {
// change code below this line
switch(action.type){
case "LOGIN":
return {authenticated: true, a: 123};
case "LOGOUT":
return {authenticated: false, b: 321};
default:
return state;
}
// change code above this line
};
const store = Redux.createStore(authReducer);
const loginUser = () => {
return {
type: 'LOGIN'
}
};
const logoutUser = () => {
return {
type: 'LOGOUT'
}
};
store.dispatch(loginUser());
store.dispatch(logoutUser());
store.dispatch(loginUser());
let test = store.getState();
console.log(test.a);
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: