Search code examples
angulartypescriptreduxngrx

ERROR TypeError: Cannot assign to read only property 'isSelected' of object '[object Object]'


I just want to update a property value of an array element in My NgRx Store Object after cloning it to avoid mutation but no success. Here is the Reducer Code:

on(
    myActions.elementDeselected,
    (state, { desiredId}) => {
    const childArrayCopy=[...state.selectedObject.childArray.slice(0)];
    const childArray = childArrayCopy.map(arrayElement=> {
        if (arrayElement.id === desiredId) {
          arrayElement.isSelected = false;
          return arrayElement;
        }
        return arrayElement;
      });

      return {
        ...state,
        selectedObject: {
          ...state.selectedObject,
          ...childArray
        }
      };
    }
  ),

Solution

  • Since arrayElement is read-only, you have to copy it, too:

    const childArray = childArrayCopy.map(arrayElement=> {
      if (arrayElement.id === desiredId) {
        arrayElement = {...arrayElement, isSelected: false}; // <===
      }
      return arrayElement;
    });
    

    That uses the object property version of spread to create a new object with a copy of the old object's properties, then updating isSelected to be false.