1
votes

I have the following two @ngrx/store reducers:

import {ActionReducer, Action} from '@ngrx/store';
import {UserAccount} from '../shared/models/useraccount.model';

export const SET_CURRENT_USER_ACCOUNT = 'SET_CURRENT_USER_ACCOUNT';
export const UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME = 'UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME';

export const currentUserAccountReducer: ActionReducer<UserAccount> = (state: UserAccount, action: Action) => {

  console.log('currentUserAccountReducer:', state, action);

  switch (action.type) {
    case SET_CURRENT_USER_ACCOUNT: {
      return action.payload;
    }
    case UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME: {
      state.firstName = action.payload;
      return state;
    }
  }
};

export const SET_AUTHENTICATED = 'SET_AUTHENTICATED';
export const SET_UNAUTHENTICATED = 'SET_UNAUTHENTICATED';

export const authenticatedReducer: ActionReducer<boolean> = (state: boolean, action: Action) => {

  console.log('authenticatedReducer:', state, action);

  switch (action.type) {
    case SET_AUTHENTICATED: {
      return true;
    }
    case SET_UNAUTHENTICATED: {
      return false;
    }
  }
};

However, for some reason when I issue a dispatch for the 1st reducer (i.e. currentUserAccountReducer) then it changes the state for the 2rd reducer (i.e. authenticatedReducer)...

Here is the dispatch causing this issue:

this.store.dispatch({type: SET_CURRENT_USER_ACCOUNT, payload: currentUserAccount});

Here is how I initialize the store in the imports section:

StoreModule.provideStore(
 {
   currentUserAccount: currentUserAccountReducer,
   authenticated: authenticatedReducer
 })

Can someone please provide advice?

edit: The issue is that authenticated ends up undefined!!

1

1 Answers

4
votes

The switch statements in your reducers do not contain default cases. You need to add default cases that return the state, as the reducers will be called for all actions - the store has no way of knowing which reducer should be called for a particular action type, so each dispatched action is passed to every reducer.