Aragorn
Aragorn

Reputation: 5289

Avoid State Mutation in NgRx Reducer

I'm new to Redux/NgRx and also fairly new to JavaScript. Trying to implement a sample state change. I understand that when I dispatch an action, in the reducer, I should be creating a new state from previous state and update part of it and return. Thus not to mutate the existing state. However, with my code below, I always see in the dev tools that my state is being mutated instead of new version. What is incorrect in the reducer?

Reducer:

export interface State {
  transactions: []
}

export function trasactionReducer (state: State, action: txActions.Actions) {

  switch (action.type) {
    case txActions.LOAD_ACCOUNT_TRANSACTION:
      return {...state};

    case txActions.STORE_ACCOUNT_TRANSACTION:
      return {...state, 
        transactions : action.payload
      };

    default:
      console.log("transactionReducer, defaul action triggerred for action: "+ action.type);
      return state;
  }

}

Upvotes: 0

Views: 1096

Answers (1)

timdeschryver
timdeschryver

Reputation: 15497

As already said in the comments, I think you aren't mutating the state directly. If you want to be sure, you can use the ngrx-store-freeze package in dev mode, this will throw an error if you do mutate the state.

Upvotes: 1

Related Questions