Search code examples
angularngxs

Error 6412 - Cannot assign to read only property


I am trying to update the state model, but I am running into an issue (because I do not have enough experience with it yet). Getting "core.mjs:6412 ERROR TypeError: Cannot assign to read only property 'decisionDate' of object '[object Object]'".

The issue is at the line I added "-->" to. What have I done wrong/what am I missing?

@Action(ClerkAction.Review.UpdateSelectedDate)  
    onUpdateSelectedDate(ctx: StateContext<ClerkStateModel>, action: ClerkAction.Review.UpdateSelectedDate) {
        const DocumentList = ctx.getState().request.documents;
        const DocumentIndex = DocumentList.findIndex(item => item.guid === action.documentGuid);  
-->     DocumentList[DocumentIndex].decisionDate = action.newDate;  

        ctx.patchState({ 
            request: {
                ...ctx.getState().request,
                documents: DocumentList
            }        
        });
    
        ctx.dispatch(new NotificationAction.Loading(false));
    }  

UPDATE and SOLUTION - 07-03-2023 So, I had to:

  • I had to clone the original item (use the react ...)

  • Then I had to replace the existing element of the collection, with the newly cloned element (along with its change).

  • Then patchState

      const DocumentList = ctx.getState().request.documents;
      const DocumentIndex = DocumentList.findIndex(item => item.guid === action.documentGuid);
      var ItemToUpdate = {...DocumentList[DocumentIndex]};
    
      ItemToUpdate.decisionDate = action.newDate;
    
      const reconstruct = addOrReplace('guid', DocumentList, ItemToUpdate);
    

Hope this helps someone.


Solution

  • Another option is to use StateOperators

    In your case it should be something like:

    ctx.setState(
      patch<ClerkStateModel>({
        documents: updateItem(
          item => item.guid === action.documentGuid,
          patch({ decisionDate: action.newDate }
        )
      })
    );