From 266789f98609a98f7bd74fdab57cd70e9fd0ec36 Mon Sep 17 00:00:00 2001 From: pedep Date: Thu, 6 Sep 2018 18:18:28 +0200 Subject: [PATCH] add stateMergeFunction to config --- README.md | 1 + src/index.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 522a6c3..3190268 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ An interface defining the configuration attributes to bootstrap `localStorageSyn * `storage` (optional) `Storage`: Specify an object that conforms to the [Storage interface](https://github.com/Microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L9708) to use, this will default to `localStorage`. * `removeOnUndefined` (optional) `boolean`: Specify if the state is removed from the storage when the new value is undefined, this will default to `false`. * `storageKeySerializer` (optional) `(key: string) => string`: Сustom serialize function for storage keys, used to avoid Storage conflicts. +* `stateMergeFunction` (optional) `(state: any, rehydratedState: any) => any`: A custom state merge function. By default, the `Object.merge({}, [..])` method is used, which does not take nested keys into account. This allows for employing libraries such as `deepmerge`, which gracefully handles nested objects, should your use-case require this behaviour. * `restoreDates` \(*boolean? = true*): Restore serialized date objects. If you work directly with ISO date strings, set this option to `false`. * `syncCondition` (optional) `(state) => boolean`: When set, sync to storage medium will only occur when this function returns a true boolean. Example: `(state) => state.config.syncToStorage` will check the state tree under config.syncToStorage and if true, it will sync to the storage. If undefined or false it will not sync to storage. Often useful for "remember me" options in login. Usage: `localStorageSync({keys: ['todos', 'visibilityFilter'], storageKeySerializer: (key) => 'cool_' + key, ... })`. In this example `Storage` will use keys `cool_todos` and `cool_visibilityFilter` keys to store `todos` and `visibilityFilter` slices of state). The key itself is used by default - `(key) => key`. diff --git a/src/index.ts b/src/index.ts index 29a2f63..e834e7e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -246,7 +246,7 @@ export const localStorageSync = (config: LocalStorageConfig) => ( (action.type === INIT_ACTION || action.type === UPDATE_ACTION) && rehydratedState ) { - state = Object.assign({}, state, rehydratedState); + state = config.stateMergeFunction ? config.stateMergeFunction(state, rehydratedState) : Object.assign({}, state, rehydratedState); } const nextState = reducer(state, action); syncStateUpdate( @@ -291,4 +291,5 @@ export interface LocalStorageConfig { restoreDates?: boolean; storageKeySerializer?: (key: string) => string; syncCondition?: (state: any) => any; + stateMergeFunction?: (state: any, rehydratedState: any) => any; }