Solution of Handle an Action in the Store

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

Can Someone please explain me this solution code

Can you post the code about which you are curious?

Redux is confusing at first, it takes time.

1 Like
const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // Change code below this line
if (action.type === 'LOGIN') {
  return{
    login: true
  }
} else {
  return state;
}
  // Change code above this line
};

const store = Redux.createStore(reducer);

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

I am unable to understand how we are able to access type property and also able to change the login property’s value.

Because our action creator…

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

returns an object with that property.

Behind the scenes, the test is dispatching that to test it. That object is passed to all the reducers (only on in this case) as the action parameter.

…also able to change the login property’s value.

The state is changed because the reducer changes the new state:

  return{
    login: true
  }

That is what reducers do - they return what you want state to become. Whatever you return becomes the new state. Remember, you never “change” the state in the sense of mutating it - you just return the next state. We could not do this:

if (action.type === 'LOGIN') {
  // never do this
  state.login = true;
  return state;
} else {
  return state;
}

Don’t mutate the state, create a completely new one. I know that may seem weird, but it is very, very important for how redux works and has some huge advantages that will become apparent as you learn more.

Does that clear it up?

1 Like

Yes that cleared all my doubts thanks dude❤️

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.