Skip to content

Instantly share code, notes, and snippets.

@peterbsmyth
Last active June 1, 2019 23:23
Show Gist options
  • Save peterbsmyth/ab907e0083f54e3133396e20f1c4de8d to your computer and use it in GitHub Desktop.
Save peterbsmyth/ab907e0083f54e3133396e20f1c4de8d to your computer and use it in GitHub Desktop.
ngrx 8 `on` function
import { createAction, props } from '@ngrx/store';
export const get = createAction(
'[Job] get'
);
export const getComplete = createAction(
'[Job] getComplete',
props<{ job: any }>()
);
export const getError = createAction(
'[Job] getError',
props<{ error: any }>()
);
export const saveOneFavorite = createAction(
'[Job] saveOneFavorite',
props<{ job: any }>()
);
export const saveOneFavoriteComplete = createAction(
'[Job] saveOneFavoriteComplete',
props<{ job: any }>()
);
export const saveOneFavoriteError = createAction(
'[Job] saveOneFavoriteError',
props<{ error: any }>()
);
export const select = createAction(
'[Job] select',
props<{ id: any }>()
);
export const filter = createAction(
'[Job] filter',
props<{ filter: any }>()
);
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { createReducer, on } from '@ngrx/store';
import { JobActions } from '../actions';
export interface State extends EntityState<any> {
loading: boolean;
error: string;
filter: string;
selectedId: string | number;
}
export const sortByJob = (a, b) => {
return a.job - b.job;
};
export const adapter: EntityAdapter<any> = createEntityAdapter<any>({
sortComparer: sortByJob,
});
export const initialState: State = adapter.getInitialState({
loading: false,
error: '',
filter: '',
selectedId: null
});
export const reducer = createReducer(
initialState,
on(
JobActions.saveOneFavorite,
JobActions.get,
(state) => ({
...state,
loading: true
})
),
on(
JobActions.getComplete,
(state, { jobCode }) => adapter.addAll(jobCode, {
...state,
loading: false
})
),
on(
JobActions.getError,
(state, { error }) => ({
...state,
loading: false,
error
})
),
on(
JobActions.select,
(state, { id }) => ({
...state,
selectedId: id
})
),
on(
JobActions.filter,
(state, { filter }) => ({
...state,
filter
})
),
on(
JobActions.saveOneFavoriteComplete,
(state, { jobCode }) => adapter.updateOne(jobCode, {
...state,
loading: false
})
),
on(
JobActions.saveOneFavoriteError,
(state, { error }) => ({
...state,
loading: false,
error
})
),
);
export const getSelectedJob = (state: State) => {
return state.selectedId;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment