Skip to content

Instantly share code, notes, and snippets.

@cha55son
Last active May 31, 2018 21:56
Show Gist options
  • Save cha55son/7d7aaecaee92ae13e2e9ea6cd8c60105 to your computer and use it in GitHub Desktop.
Save cha55son/7d7aaecaee92ae13e2e9ea6cd8c60105 to your computer and use it in GitHub Desktop.
NgRx Boilerplate for a resource action and it's side effects
/**
* TYPES =======================================================
*/
export interface MyResourcesState extends EntityState<MyResource> {
getAllLoading: boolean;
getAllLoaded: boolean;
getAllLoadedError: Error | null;
}
/**
* ACTIONS =======================================================
*/
export enum Types {
GET_ALL = 'Get All',
GET_ALL_LOADING = 'Get All Loading',
GET_ALL_FINISHED = 'Get All Finished',
}
export class GetAll implements Action { // Effect
readonly type = Types.GET_ALL;
}
export class GetAllLoading implements Action { // Reducer Action
readonly type = Types.GET_ALL_LOADING;
constructor(public isLoading: boolean) { }
}
export class GetAllFinished implements Action { // Reducer Action
readonly type = Types.GET_ALL_FINISHED;
constructor(public succeeded: boolean, public anError: Error | null) { }
}
export type MyResourcesAction = GetAllLoading | GetAllFinished;
/**
* REDUCER =======================================================
*/
export const myResourcesAdapter = createEntityAdapter<MyResource>();
function getInitialState(): MyResourcesState {
return myResourcesAdapter.getInitialState({
getAllLoading: false,
getAllLoaded: false,
getAllLoadedError: null
});
}
export function myResourcesReducer(
state: MyResourcesState = getInitialState(),
action: MyResourcesAction
): MyResourcesState {
switch (action.type) {
case Types.GET_ALL_LOADING:
return { ...state, getAllLoading: action.isLoading };
case Types.GET_ALL_FINISHED:
return { ...state, getAllLoaded: action.succeeded, getAllLoadedError: action.anError };
default:
return state;
}
}
/**
* SELECTORS =======================================================
*/
export const selectMyResourcesState = createFeatureSelector<MyResourcesState>('myResources');
export const selectMyResourcesGetAllLoading = createSelector(selectMyResourcesState, (state: MyResourcesState) => state.getAllLoading);
export const selectMyResourcesGetAllLoaded = createSelector(selectMyResourcesState, (state: MyResourcesState) => state.getAllLoaded);
export const selectMyResourcesGetAllLoadedError = createSelector(selectMyResourcesState, (state: MyResourcesState) => state.getAllLoadedError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment