Question about solution of Redux in the Challenge Guide: Handle Action in the Store

Currently in the hint page we got this solution

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"
  };
};

Then I have my own solution:

const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  // Change code below this line
  state.login = action.type === 'LOGIN'

  return state
  // Change code above this line
};

const store = Redux.createStore(reducer);

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

Meanwhile in the test case, it says:

Dispatching loginAction should update the login property in the store state to true.

In that case, my code should be able to pass the test since it updates the login prop in the state to true. But it won’t, why?

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

2 Likes

Because you’re mutating the state.

The function should take the state object, apply the action to it, then produce a new state object. Yours takes the state, applies the action to it, and returns the same state object.

(state1, action) => state2

Whereas yours is

(state1, action) => state1

The point of Redux is that you represent the state of an application as an object. Then it lets you apply changes one by one to that object and easily track when a change has happed.

It’s an alternative to what you’ve done, and it’s much simpler overall.

The way you’ve done it doesn’t need a reducer function: you could literally just have an object and then mutate parts of it.

The problem then is how do you tell if something changed?

If you return the same object it’s not obvious. There would need to be some different logic that has to look at the object and figure out what happened – you would need something that watches the object for changes and notifies the program when a change occurs (and what that change is).

If you return a new object every time something changes, then it’s obviously changed. Changes are really easy to track because in the app you can just say “is this state the same as the last state? If it is, do nothing. Otherwise make changes”.

Libraries that commonly use Redux (like React) work by taking some data and rendering some UI based on it. When that data changes, they rebuild the bits of the UI that need changing.

So if you just keep giving your React code the same object, the UI won’t change, nothing will happen.

3 Likes

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