Skip to content

Instantly share code, notes, and snippets.

@itayod
Last active June 10, 2019 15:40
Show Gist options
  • Save itayod/3e20ee3658f539db3745c1519c56a38c to your computer and use it in GitHub Desktop.
Save itayod/3e20ee3658f539db3745c1519c56a38c to your computer and use it in GitHub Desktop.
import {ActionReducer, Action} from '@ngrx/store';
import {merge, pick} from 'lodash-es';
import {LocalStorageService} from './local-storage.service';
export function storageMetaReducer<S, A extends Action = Action>(saveKeys: string[],
localStorageKey: string,
storageService: LocalStorageService
) {
let onInit = true; // after load/refresh…
return function(reducer: ActionReducer<S, A>) {
return function(state: S, action: A): S {
// get the next state.
const nextState = reducer(state, action);
// init the application state.
if (onInit) {
onInit = false;
const savedState = storageService.getSavedState(localStorageKey);
return merge(nextState, savedState);
}
// save the next state to the application storage.
const stateToSave = pick(nextState, saveKeys);
storageService.setSavedState(stateToSave, localStorageKey);
return nextState;
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment