The state of our application will be stored in an object called auth with the values – userProfile and idLoggedIn.
{ auth: {
isLoggedIn,
userProfile } }
We will create a reducer file called auth.reducer.ts under the store folder to add our state as an interface.
auth.reducer.ts:
import { Action, createReducer, on } from '@ngrx/store';
import * as authActions from './auth.actions';
export interface AuthState {
userProfile: any;
isLoggedIn: boolean;
}
export const initialState: AuthState = {
userProfile: null,
isLoggedIn: false,
};
const authReducerInternal = createReducer(
initialState,
on(authActions.loginComplete, (state, { profile, isLoggedIn }) => {
return {
...state,
userProfile: profile,
isLoggedIn,
};
}),
on(authActions.logoutComplete, (state, {}) => {
return {
...state,
userProfile: null,
isLoggedIn: false,
};
})
);
export function authReducer(
state: AuthState | undefined,
action: Action
): AuthState {
return authReducerInternal(state, action);
}
The AuthState represents the value the auth property has in our state. The reducer only handles anything that goes on inside of the auth property.
We have set the initialState and create the reducer to pass the initialState. We must add state manipulation when a specific action comes in.
We will add the profile we received if the login is completed with the action loginComplete, and also set the isLoggedIn. We will reset the userProfile to null and isLoggedIn to false when the action logoutComplete is thrown.