Skip to content

Instantly share code, notes, and snippets.

@alanxone
Last active June 11, 2018 09:05
Show Gist options
  • Save alanxone/777285572dad5567a2fe18f1d291be64 to your computer and use it in GitHub Desktop.
Save alanxone/777285572dad5567a2fe18f1d291be64 to your computer and use it in GitHub Desktop.
NGRX Tutorial - Auth Reducers
// NGRX Complete Tutorial Without Pain (Angular6 / RxJS6)
// https://medium.com/@andrew.kao/ngrx-complete-tutorial-without-pain-angular6-rxjs6-5511b8cb8dac
import { ActionReducer, Action } from '@ngrx/store';
import * as auth from '(auth action path)';
// Here is the final state required by the app
export interface State {
isAuthenticated: boolean;
// Name is what we passed in "Actions" as payload, thus it can be a model if needed
userName: string | '';
// This is used for showing usage when login is failed
attemptLoginFailed: boolean;
}
// Here is the initial state set if no changes happened
export const defaultState: State = {
isAuthenticated: false;
userName: '';
attemptLoginFailed: false;
}
export function reducer(state: defaultState, action: auth.AuthActions): State {
switch (action.type) {
// Case can be more complex
// "Login" is not put since it's not used for representing a status (State)
case auth.Success:
return {
isAuthenticated: true,
// The username is retrieved from the "Action"
// In production, user data should be defined as a model
// Retrieving user data like, `user: action.payload.user <- a model`
userName: action.payload,
attemptLoginFailed: false,
};
case auth.Failed:
return {
isAuthenticated: false,
userName: '',
attemptLoginFailed: true,
};
default:
return state;
}
}
// Use "Const" for getting read-only data managed by current "Reducer"
export const isAuthenticated = (state: State) => state.isAuthenticated;
export const getUserName = (state: State) => state.userName;
export const isRisky = (state: State) => state.attemptLoginFailed;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment