1

I'm getting this error:

Cannot assign to read only property 'active' of object '[object Object]'

I know that the message means, I can't work on the state directly. Overall i'm trying to switch a boolean. my reducer is

on(ConfigsActions.toggle, (state, data) => {
    const clone = getAllConfigs.projector();
    const conf = clone.find(f => f.id === data.config.id);
          conf.domains.forEach(domain => {
              domain.features.forEach(feature => {
                if(feature.settingId === data.setting.settingId) {
                  feature.active = !feature.active;
                }
                else {
                  feature.components.forEach(component => {
                    if(component.settingId === data.setting.settingId) {
                      component.active = !component.active;
                    }
                  })
                }
              })
            }
          );

    return configsAdapter.updateOne({id: conf.id, changes: {
      domains: conf.domains
    }}, state);
  })

What am I doing wrong? Maybe the reducer is not where I should make those changes?

H3AR7B3A7
  • 4,366
  • 2
  • 14
  • 37
  • 2
    You are mutating the objects. You need to return a new object and overwrite the value that needs to be updated. e.g.: `return { ...state, /* update whatever needs updating */}` Or for a nested object: `return { ...state, nestedObject: {...nestedObject, /* update value here*/}}`. – H3AR7B3A7 Jul 26 '22 at 11:21
  • isn't "clone" a new object? In my knowledge that should work. – TheBadBossy Jul 26 '22 at 11:52
  • Isn't `clone` a reference to the original slice of state ? I'm not sure though. – Alain Boudard Jul 26 '22 at 12:04
  • It's not clear from the code sample if `clone` is a new object. If you're getting a read-only assignment error, it's highly unlikely that it's a new, unfrozen object. – Brandon Taylor Jul 26 '22 at 12:40
  • i get it. gonna go and refactor a bit of code now. – TheBadBossy Jul 26 '22 at 12:57

1 Answers1

1

State in the NgRx store is immutable. You're mutating it directly, which gives this error (because the Object is frozen). https://ngrx.io/guide/store/configuration/runtime-checks#strictstateimmutability

Instead, create a clone, or use the rest operator to mutate state. You can also take a look at ngrx-immer which makes this easy. With it, you can simply mutate the state in a "normal way".

timdeschryver
  • 14,415
  • 1
  • 19
  • 32