Skip to content

Instantly share code, notes, and snippets.

@appelstroop
Last active May 6, 2020 23:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save appelstroop/2e2ac063640b362aab612f6085cb1e7e to your computer and use it in GitHub Desktop.
Save appelstroop/2e2ac063640b362aab612f6085cb1e7e to your computer and use it in GitHub Desktop.
Redux persist automerge with immutable state
/* Created a custom automerge for immutable
Adapted from https://github.com/rt2zz/redux-persist/blob/master/src/stateReconciler/autoMergeLevel2.js
*/
export default function autoMergeLevel2Immutable(
inboundState,
originalState,
reducedState,
{ debug }
) {
let newState = { ...reducedState }
// only rehydrate if inboundState exists and is an object
if (inboundState && typeof inboundState === 'object') {
Object.keys(inboundState).forEach(key => {
// ignore _persist data
if (key === '_persist') return
// if reducer modifies substate, skip auto rehydration
if (originalState[key] !== reducedState[key]) {
if (process.env.NODE_ENV !== 'production' && debug)
console.log(
'redux-persist/stateReconciler: sub state for key `%s` modified, skipping.',
key
)
return
}
if (isPlainEnoughObject(reducedState[key].toJS())) {
// if object is plain enough shallow merge the new values (hence "Level2")
newState[key] = newState[key].merge(inboundState[key])
return
}
// otherwise hard set
newState[key] = inboundState[key]
})
}
if (
process.env.NODE_ENV !== 'production' &&
debug &&
inboundState &&
typeof inboundState === 'object'
)
console.log(
`redux-persist/stateReconciler: rehydrated keys '${Object.keys(
inboundState
).join(', ')}'`
)
return newState
}
function isPlainEnoughObject(o) {
return o !== null && !Array.isArray(o) && typeof o === 'object'
}
@fxckdead
Copy link

fxckdead commented May 6, 2020

Thanks for this!

If someone is using seamless-immutable the gist will not work as it's, you will need to change line 27 to use .asMutable() instead of .toJS()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment