Created
May 25, 2019 13:40
-
-
Save itayod/b6698d406160fd155a1d7df01a4672d9 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'; | |
function setSavedState(state: any, localStorageKey: string) { | |
localStorage.setItem(localStorageKey, JSON.stringify(state)); | |
} | |
function getSavedState(localStorageKey: string): any { | |
return JSON.parse(localStorage.getItem(localStorageKey)); | |
} | |
// the keys from state which we'd like to save. | |
const stateKeys = ['layout.theme']; | |
// the key for the local storage. | |
const localStorageKey = '__app_storage__'; | |
export function storageMetaReducer<S, A extends Action = Action> (reducer: ActionReducer<S, A>) { | |
let onInit = true; // after load/refresh… | |
return function(state: S, action: A): S { | |
// reduce the nextState. | |
const nextState = reducer(state, action); | |
// init the application state. | |
if (onInit) { | |
onInit = false; | |
const savedState = getSavedState(localStorageKey); | |
return merge(nextState, savedState); | |
} | |
// save the next state to the application storage. | |
const stateToSave = pick(nextState, stateKeys); | |
setSavedState(stateToSave, localStorageKey); | |
return nextState; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment