rehydrate State is not working with FeatureModule state
See original GitHub issueI have a FeatureModule for Authentication that is using StoreModule.forFeature(‘auth’ and therefore creates an auth object on the store. This auth object i want to sync with the localStorage. The rehydrate function only listens on the @ngrx/store/init event. However at this time the auth if not yet set on the store You have to also listen for the @ngrx/store/update-reducers event. This is called afterwards (for each FeatureModule) and overwrites the auth with it’s initialState value.
So the whole ngrx-store-localstorage module rehydrate is not working for FeatureModules (StoreModule.forFeature) But actually thats the whole point of this so it is not useable…
Update: I just diged in it and it seems, that rehydrate actually gets called for every added FeatureModule on the @ngrx/store/update-reducers event. However in the meanwhile, the store got synced again to the localstorage and has overwritten the auth. So the thing is, that when the event is @ngrx/store/update-reducers then please don’t sync it to the localStorage as it overwrites the state that should get rehydrated
Update 2: I made a fixed version of localStorageSync, it may not be very sophisticated and it actually has to cover more configuration, but for me it does the trick for now: `export const localStorageSyncFixed = (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 && rehydratedState) state = Object.assign({}, state, rehydratedState);
// Also on Update Reducers rehydrate the state
if (action.type === UPDATE && rehydratedState)
state = Object.assign({}, state, rehydratedState);
const nextState = reducer(state, action);
if (action.type !== UPDATE && action.type !== INIT)
syncStateUpdate(nextState, stateKeys, config.storage, config.storageKeySerializer, config.removeOnUndefined);
return nextState;
}; };`
Issue Analytics
- State:
- Created 6 years ago
- Comments:5
Top GitHub Comments
I’m solving with the following:
@darbio No, i‘m not using this functionality. I‘m doing it manually with localstorage at the initial state