Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions spec/index_spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
declare var beforeEachProviders, it, describe, expect, inject;
require('es6-shim');
import { syncStateUpdate, rehydrateApplicationState, dateReviver } from '../src/index';
import { syncStateUpdate, rehydrateApplicationState, dateReviver, mergePartialStates } from '../src/index';
import * as CryptoJS from 'crypto-js';

// Very simple classes to test serialization options. They cover string, number, date, and nested classes
Expand Down Expand Up @@ -374,4 +374,21 @@ describe('ngrxLocalStorage', () => {
expect(t1 instanceof TypeA).toBeTruthy();
expect(finalState.simple instanceof TypeA).toBeFalsy();
});
});

it('merges partial states', () => {
const keyDef = ['foo', { bar: ['baz'] }];
expect(
mergePartialStates(
keyDef,
{ bar: {baz: 123, nitch: 456} },
{ foo: 'hello', bar: {baz: 1} },
)
).toEqual({
foo: 'hello',
bar: {
baz: 1,
nitch: 456
}
});
});
});
33 changes: 32 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export const localStorageSync = (config: LocalStorageConfig) => (
(action.type === INIT_ACTION || action.type === UPDATE_ACTION) &&
rehydratedState
) {
state = Object.assign({}, state, rehydratedState);
state = mergePartialStates(stateKeys, state, rehydratedState);
}
const nextState = reducer(state, action);
syncStateUpdate(
Expand All @@ -246,6 +246,37 @@ export const localStorageSync = (config: LocalStorageConfig) => (
};
};

export const mergePartialStates = (stateKeys: (string | { [idx: string]: null | undefined | string[] })[], currentState: {}, rehydratedState: {}) => {
let finalState = { ...currentState };

stateKeys.map((key) => {
if ( typeof key === 'string' ) {
finalState = {
...finalState,
[key]: rehydratedState[key],
};
} else {
const name = Object.keys(key)[0];
const newValues = {};

const keys = key[name]
if (keys) {
keys.map((key) => newValues[key] = rehydratedState[name][key])
}

finalState = {
...finalState,
[name]: {
...finalState[name],
...newValues,
},
};
}
});

return finalState;
}

/*
@deprecated: Use localStorageSync(LocalStorageConfig)

Expand Down