Home > Mobile >  how to return ActionReducerMap properly
how to return ActionReducerMap properly

Time:04-24

I have defined my reducers like this

    import { Action, ActionReducerMap, createAction, createReducer, on } from '@ngrx/store'
import AppUser from 'src/app/shared/models/app-user';
import { AuthActions } from '../auth.action.types';


export interface AppState {
  loggedInUser: AppUser
}

export const initialGlobalState: AppState = {
  loggedInUser: undefined,
};

export const authReducer = createReducer(
  initialGlobalState,

  on(AuthActions.loginSuccess, (state, action) => {
    return {
    // ...state,
      loggedInUser: action.loggedInUser,
    };
  }),

  on(AuthActions.logout, (state, action) => {
    return {
  //   ...state,
      loggedInUser: undefined,
    };
  }),
);

export const reducers: ActionReducerMap<AppState> = {
  globalState: authReducer,
};

and this reducer is hooked into app.module.ts like this.

    StoreModule.forRoot(reducers),
StoreDevtoolsModule.instrument({
  maxAge: 25, // Retains last 25 states
  logOnly: environment.production, // Restrict extension to log-only mode
}),
EffectsModule.forRoot([AuthEffects])

but I am getting compile error that

TS2322: Type '{ globalState: ActionReducer<AppState, Action>; }' is not assignable to type 'ActionReducerMap<AppState, Action>'.

What am I doing wrong ? kindly help

CodePudding user response:

Try to add response types for reducer cases

export const authReducer = createReducer(
  initialGlobalState,

  on(AuthActions.loginSuccess, (state, action): AppState => {
    return {
    // ...state,
      loggedInUser: action.loggedInUser,
    };
  }),

  on(AuthActions.logout, (state, action): AppState => {
    return {
  //   ...state,
      loggedInUser: undefined,
    };
  }),
);

UPD@2

import { Action, ActionReducerMap, createReducer, on } from '@ngrx/store';
import * as fromAuth from './auth.actions';

export interface State {
  model: State | null;
}

const initialState: State = {
  model: null,
};

const authReducer = createReducer(
  initialState,

  on(fromAuth.Load, (state) => ({ ...state, model: null }))
);

function reducer(state: State | undefined, action: Action): State {
  return authReducer(state, action);
}

export const reducers: ActionReducerMap<{ globalAuth: State }> = {
  globalAuth: reducer,
};

CodePudding user response:

I believe you need to create another interface where you set your global property, you could create another file for this

index.ts

import * as fromAuth from './reducers/auth.reducer';

export interface State {
 global: fromAuth.AppState,
 // you can add more states here that will be need it for root,
 // for example:
 // preferences: fromPreferences.State
}

export const reducers: ActionReducerMap<State> = {
 global: fromAuth.authReducer
 // preferences: fromPreferences.reducer
}

app.module.ts

import { reducers } from './store/auth/index';
...
...
imports: [
  StoreModule.forRoot(reducers),
  ...
]
  • Related