Search code examples
javascriptangularupgradengrxreadonly

Angular 10 - NGRX Upgrade Issues : Cannot add property x object is not extensible and Cannot assign to read only property x of object


After upgrading Angular 4 to 10 and NGRX version (to v 9) I am getting multiple errors while trying to do any operation.

My application is breaking every time I am making a http call.

I am getting below errors and sometimes there is no errors/warnings but the page is breaking.

  1. Cannot add property xxx, object is not extensible
  2. Cannot assign to read only property xxx of object '[object Object]'

Solution

  • The issue is not related to Angular, it is NGRX version upgrade issue

    store objects are readonly so any update to store data in action,reducer,effect and selector will throw a similar err you have mentioned

    to fix this:

    1. We always need to send a new reference from the selector if we want to do any kind of update/assignment operation on the object in the component.
    2. avoid any kind of update to the payload in store(action/effect/reducer) do the changes in component.
    3. If we want do any modification to the payload and use it in reducer/effect take a new reference.

    For creating a new reference you can use

    1. ... operator(tricky one for nested objects)

    2. JSON.parse(JSON.stringfy(data))(not full proof for nested objects and all type)

    3. Object.assign({}, obj);

    4. cloneDeep (if you are using lodash) or write custom method to deep clone object

    Also you may get few syntax errors , Please use the link

    https://ngrx.io/guide/migration and read the guide for the version you are migrating from

    https://ngrx.io/guide/migration/v8

    workaround : In the previous version of NgRx, runtime Immutability checks were opt-in. In version 9 and higher , the immutability runtime check is turned on by default.

    so you can set it to false :

    @NgModule({
      imports: [
        StoreModule.forRoot(reducers, {
          runtimeChecks: {
            strictStateImmutability: false,
            strictActionImmutability: false,
          },
        }),
      ],
    })
    export class AppModule {}
    

    your code will work as earlier but this is not the correct solution.

    use this link for more information

    https://medium.com/ngrx/announcing-ngrx-version-9-immutability-out-of-the-box-customizable-effects-and-more-e4cf71be1a5b