Updating the NgRx Auth reducer

Now, let's update the reducer. Our initialState will have the auth object, which we will create when the RegisterApp action is dispatched. We will also have an authenticated property, which will be boolean, for whether the user is authenticated or not, and properties for whether the login is in progress or it failed. We will update the state based on the authentication actions.

Let's react to different actions of authentication here in our reducer:

import { AuthAction, AuthActionTypes } from './auth.actions';
import * as auth0 from 'auth0-js';

...

export interface AuthState {
authenticated: boolean;
auth?: any;
loginInProgress: boolean;
loginFailed: boolean
;
}

...

let authenticated = false;
if (localStorage.getItem('access_token')) {
authenticated = true;
}

export const initialState: AuthState = {
auth: undefined,
authenticated,
loginInProgress: false,
loginFailed: false,
}
;

export function authReducer(
state: AuthState = initialState,
action: AuthAction
): AuthState {
switch (action.type) {
case AuthActionTypes.Login: {
state = {
...state,
loginInProgress: true,
};
break;
}
case AuthActionTypes.LoginFailure: {
return {
...state,
loginInProgress: false,
loginFailed: true,
};
break;
}

case AuthActionTypes.LoginSuccess: {
return {
...state,
loginInProgress: false,
authenticated: true,
};
break;
}

case AuthActionTypes.RegisterApp: {
const { clientId, callbackUrl, domain } = action.payload;
const auth = new auth0.WebAuth({
clientID: clientId,
domain,
responseType: 'token id_token',
redirectUri: callbackUrl,
scope: 'openid'
});

state = {
...state,
auth,
};
return state;
}

case AuthActionTypes.Logout: {
return {
...state,
authenticated: false,
};
break;
}
}
return state;
}

Let's also remove the existing selectors from auth.selectors.ts file, as our state structure is updated.

Now, we have our reducer's setup completed. Next, we need to add some effects that are going to call asynchronous calls when authentication is being processed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.94