Zireael
Zireael

Reputation: 1035

Update value in array in reducer

I have a reducer

const initialState = {
    elements: [{"flag": false}, {"flag": false}]
};

const checkReducer = function (state = initialState, action) {
    switch (action.type) {
        case CHANGE_CHECK:

            return {...state, //here I want update element by index, that pass in action};

I need to update an existing value in array elements, that I get by the index passed in action. I can do it like this

state.elements[action.key] = {"flag": !action.flag}

but then I'll change existing state. according to the redux principles, I can't do it. So I have to use spread operator and change new object. But I don't know how to use it this way. Tried something like this

...state, elements[action.index]: {"flag": !action.flag}] 

but it isn't worked. Is there a way to do what I want?

Upvotes: 0

Views: 233

Answers (1)

Federkun
Federkun

Reputation: 36999

return {
  ...state,
  elements: state.elements.map((element, index) => {
    if (index === action.key) {
      return {"flag": !action.flag}
    }

    return element
  })
}

array#map will create a new array, and change only the item whose index match action.key.

If you find this process tedious, you could use libraries that let mutate your state while keeping the reducer returning new state. One of those is immer.

Upvotes: 2

Related Questions