s_kamianiok
s_kamianiok

Reputation: 473

Change object key property in reducer

I have two values from the server - old value and new value. Inside my redux store I need to change object key from old value to a new value (edit key value) and attach array of items from old object key to replaced new object key. What is the best approach to do it?

I tried do it something like this:

const handleEditFilter = (state, { payload }) => {
  const { newValue, oldValue } = payload;
  return {
    ...state,
    regions: {
      ...state.regions,
      list: {
        ...state.regions.list,
        [newValue]: [...state.regions.list[oldValue]],
      },
    },
  };
};

But it's just create a new object with array items from old array. How to actually replace key name of object and attach items from old key?

Upvotes: 1

Views: 1780

Answers (1)

Sulthan
Sulthan

Reputation: 130200

First of all, copy the inner list:

const list = { ...state.regions.list };

then replace the value:

list[newValue] = list[oldValue];
delete list[oldValue];

Then update state:

return {
  ...state,
  regions: {
     ...state.regions,
     list
  }
};

To perform immutable operations on nested objects, I prefer to use a library, e.g. icepick, which would make the operation a bit more readable (a chain of getIn, unsetIn and setIn).

Upvotes: 2

Related Questions