I
I
ivaboyto2020-12-24 22:05:40
redux
ivaboyto, 2020-12-24 22:05:40

How to add a field in an object in a reducer?

The store has an array like this:

plans: [
  [ {id: 1},{id: 2},{id: 3} ],
  [ {id: 4},{id: 5},{id: 6} ],
  [ {id: 7},{id: 8},{id: 9} ],
]

The following arrives in the reducer:
case "TEST":
console.log(action.someID) // 3
console.log(action.value) // "SomeValue"
  return {
    ...state,
    plans: ???
  };


It is necessary to immutably return the plans array, but in the object with id equal to action.someID, add a new field called value which will be equal to action.value.

So in this case, the output should look like this:
plans: [
  [ {id: 1},{id: 2},{id: 3, value: "SomeValue"} ],
  [ {id: 4},{id: 5},{id: 6} ],
  [ {id: 7},{id: 8},{id: 9} ],
]


My brain exploded from nesting, please help me, I always have an array without a new field returned.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-24
@ivaboyto

return {
  ...state,
  plans: state.plans.map(n => {
    const item = n.find(m => m.id === action.id);
    return item
      ? n.map(m => m === item ? { ...m, value: action.value } : m)
      : n;
  }),
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question