Search code examples
reactjsreduximmutabilitymutable

immutably update array of objects in redux


I am mutating state here, but I don't want to! All my attempts to not mutate state have come back with syntax errors, so I have turned here.

this is my redux data structure:

controls: (array)[
    0:
        id: "e06c5fbf-6d57-4f5b-a601-bfc4ad265def"
        status: 'complete'
        files: []
    1:
        id: "e06c5fbf-6d57-4f5b-a601-bfc4ad265def"
        status: 'complete'
        files: []
    ...
    ]

// and my reducer

export default function frameworkReducer(state = initialState, action) {
    case RECEIVE_CONTROL_STATUS_UPDATE:
            const index = action.payload.index;
            const newState = {...state};
            newState.controls[index] = { ...state.controls[index], status: action.payload.value };
            return newState

Solution

  • This worked for me:

    // reducer

        let index = action.payload.index
        let controls = [...state.controls];
        controls[index] = {...controls[index], status: action.payload.value};
        return {...state, controls}