Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
      };
    }
  ),
like image 578
DevLoverUmar Avatar asked Jan 01 '23 07:01

DevLoverUmar


1 Answers

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.

like image 119
T.J. Crowder Avatar answered Jan 13 '23 12:01

T.J. Crowder