Last active
June 10, 2019 15:40
-
-
Save itayod/3e20ee3658f539db3745c1519c56a38c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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