Handle an Action in the Store

Tell us what’s happening:

Your code so far


const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // change code below this line
  switch(action.type){
    case 'LOGIN':
      state.login = true;
      break
  }
  return state;
  // change code above this line
};

const store = Redux.createStore(reducer);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/redux/handle-an-action-in-the-store

One of the main ideas in Redux is that your state should be immuteable. So when you do state.login = true; your editing the object directly and changing the original object. This is against the philosophy of redux and what you should be doing is return a new object with all of the current objects stuff in it, and then including the change.


case "LOGIN":
    return {...state, login: true};

This is using some ES6 and some syntactic sugar to copy the old object to a new object. Also normally the structure of a reducer in redux is like so:


const reducer = (state = defaultState, action) => {
   switch (action.type) {
       case "LOGIN":
            return {...state, login: true};
      default:
           return state;
    }
}


Hope this helps!

4 Likes

The blurb tells you to create a state object with login set to true

{login: true}

although the correct way to solve this would be with a switch at this point of the tutorial we are not there yet so the answer should look something like this

if(action.type === ‘LOGIN’ ){
return {login: true}
} return state;

3 Likes