Skip to content

Instantly share code, notes, and snippets.

@dojchek
Last active July 24, 2017 21:50
Show Gist options
  • Save dojchek/c27ec375758417ba38d569fe455f5ec9 to your computer and use it in GitHub Desktop.
Save dojchek/c27ec375758417ba38d569fe455f5ec9 to your computer and use it in GitHub Desktop.
localstorage: ngrx 4 + prod
export function localStorageSyncWrapper(reducer: any) {
return localStorageSync({keys: ['filter', 'auth']}, reducer);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
StoreModule.forRoot(reducers, {metaReducers: [localStorageSyncWrapper]})
]
})
export class AppModule {
}
export function localStorageSync(config: LocalStorageConfig, reducer: any) {
if (config.storage === undefined) {
config.storage = localStorage || window.localStorage;
}
if (config.storageKeySerializer === undefined) {
config.storageKeySerializer = (key) => key;
}
const stateKeys = validateStateKeys(config.keys);
const rehydratedState = config.rehydrate ? rehydrateApplicationState(stateKeys, config.storage, config.storageKeySerializer) : undefined;
return function (state = rehydratedState, action: any) {
/*
Handle case where state is rehydrated AND initial state is supplied.
Any additional state supplied will override rehydrated state for the given key.
*/
if (action.type === INIT_ACTION && rehydratedState) {
state = Object.assign({}, state, rehydratedState);
}
const nextState = reducer(state, action);
syncStateUpdate(nextState, stateKeys, config.storage, config.storageKeySerializer, config.removeOnUndefined);
return nextState;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment