Last active
July 24, 2017 21:50
-
-
Save dojchek/c27ec375758417ba38d569fe455f5ec9 to your computer and use it in GitHub Desktop.
localstorage: ngrx 4 + prod
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
export function localStorageSyncWrapper(reducer: any) { | |
return localStorageSync({keys: ['filter', 'auth']}, reducer); | |
} | |
@NgModule({ | |
declarations: [ | |
AppComponent | |
], | |
imports: [ | |
StoreModule.forRoot(reducers, {metaReducers: [localStorageSyncWrapper]}) | |
] | |
}) | |
export class AppModule { | |
} |
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
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