Paweł Baca
Paweł Baca

Reputation: 888

Redux reducers, object key value

I have hashMap in my redux store, I want change isChecked value for children id: 2. Is it good to make it on state like this (operating on state)?

My hashMap

const childrens = {
  1: { name: "Test", isChecked: false },
  2: { name: "test2", isChecked: false }
};

Here is my reducer

export const childrensReducer = (state = childrens, action) => {
  switch (action.type) {
    case "SELECT_CHILDREN":
      const id = 2;
      state[id].isChecked = !state[id].isChecked;
      return { ...state };
  }
};

Upvotes: 0

Views: 1651

Answers (3)

SuleymanSah
SuleymanSah

Reputation: 17888

The problem is that you are mutating the state in the reducer with this line:

state[id].isChecked = !state[id].isChecked;

Why immutability is required by redux can be found in official docs:

https://redux.js.org/faq/immutable-data

One way to do is: ( I expect you send id through action.id )

    case "SELECT_CHILDREN":
      return {
        ...state,
        [action.id]: {
          ...state[action.id],
          isChecked: !state[action.id].isChecked
        }
      };

These kind of state operations are easier when an array is used for state.

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282120

Its not a good practise to mutate state, since react depends on immutability for a lot of its features.

Consider for example lifecycle methods or rerender after comparing state/props(PureComponents)

The problem with mutating state is that when these values are passed as props to children and you try to take some decision on them based on whether the state has updated, the previous props and the current props both will hold the same value and hence the comparisons may fail leading to buggy application

The correct way to update state is

case "SELECT_CHILDREN": 
  const id = 2;
  return {
    ...state,
    [id]: {
      ...state[id],
      isChecked: !state[id].isChecked
    }
  };

Upvotes: 2

AdamKniec
AdamKniec

Reputation: 1727

It's not a good practice to mutate the state like you did.

There are different approaches of changing the state. Take a look at the below link to get some more information and examples. https://www.freecodecamp.org/news/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5/

Upvotes: 1

Related Questions