Created
June 6, 2021 09:06
-
-
Save wildeyes/45be25f43bda72e454f26f5c63fba9f9 to your computer and use it in GitHub Desktop.
MST Persist
This file contains hidden or 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
import { onSnapshot, applySnapshot, getSnapshot } from 'mobx-state-tree'; | |
interface PersistenceWhitelist<T> { | |
key: string; | |
getPersistence: (T) => Partial<T>; | |
} | |
/** | |
* Rehydrate a store from localstorage. Set up an event to persist store data to localstorage. | |
* @param key localstorage key | |
* @param opts store any mst store instance | |
*/ | |
export function withPersistence<T>( | |
store: T, | |
opts: { key: string; whitelist: PersistenceWhitelist<T>[] } | |
): T { | |
const { key, whitelist } = opts; | |
onSnapshot(store, (_snapshot: T) => { | |
const snapshot: Partial<T> = {}; | |
for (const item of whitelist) { | |
snapshot[item.key] = item.getPersistence(_snapshot[item.key]); | |
} | |
const data = JSON.stringify(snapshot); | |
try { | |
localStorage.setItem(key, data); | |
} catch (err) { | |
if (process.env.NODE_ENV === 'development') { | |
console.warn(err); | |
} | |
// silence errors about sizing. | |
} | |
}); | |
const data = localStorage.getItem(key); | |
if (data) { | |
const existingSnapshot = getSnapshot<T>(store); | |
const persistedData = JSON.parse(data); | |
const snapshot = { | |
...existingSnapshot, | |
...persistedData, | |
}; | |
try { | |
applySnapshot(store, snapshot); | |
} catch (err) { | |
if (process.env.NODE_ENV === 'development') { | |
console.warn(err); | |
} | |
// discard snapshot, for it is invalid | |
} | |
} | |
return store; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment