Search code examples
angularngrx-store

ngrx-store strictStateImmutability does not prevent state from being replaced


I'm going to do my best to explain this question. With strictStateImmutability you are not allowed to modify a property of state directly like this.

export const reducer = createReducer(initialState,
  on(addTodo, (state, { todo }) => {
    // Violation 1: we assign a new value to `todoInput` directly
    state.todoInput = ''
    // Violation 2: `push` modifies the array
    state.todos.push(todo)
  })
);

It does not seem to care if you replace state directly like this

export const reducer = createReducer(initialState,
  on(addTodo, (state, { todo }) => {
    // No violation
    state = initialState
  })
);

Doesn't this also violate strict state immutability?


Solution

  • I believe strictStateImmutability calls Object.freeze on state object. It's not going to let you change any of its properties (like you mentioned in the post) but you can replace the entire object with something else.

    Take a look at this example:

    let state = { foo: 'bar' };
    Object.freeze(state);
    state.foo = 'test'; // won't work
    state = { foo: 'test' }; // will replace the entire object and Object.freeze doesn't matter