UNPKG

@snipsonian/observable-state

Version:

Observable-state snippets (redux-like)

48 lines (47 loc) 1.77 kB
import mergeObjectPropsDeeply from '@snipsonian/core/es/merge/mergeObjectPropsDeeply'; import localStorage from '@snipsonian/browser/es/storage/localStorage'; import sessionStorage from '@snipsonian/browser/es/storage/sessionStorage'; export function determineInitialState({ initialState, stateStorageConfig, }) { if (!stateStorageConfig) { return initialState; } const { local, session, custom } = stateStorageConfig; let combinedStorageState = initialState; if (local && localStorage.isSupported) { combinedStorageState = mergeObjectPropsDeeply(combinedStorageState, localStorage.read({ key: local.browserStorageKey, defaultValue: {}, })); } if (session && sessionStorage.isSupported) { combinedStorageState = mergeObjectPropsDeeply(combinedStorageState, sessionStorage.read({ key: session.browserStorageKey, defaultValue: {}, })); } if (custom) { combinedStorageState = mergeObjectPropsDeeply(combinedStorageState, custom.readFromStorage()); } return combinedStorageState; } export function saveStateToStorage({ state, stateStorageConfig, }) { if (!stateStorageConfig) { return; } const { local, session, custom } = stateStorageConfig; if (local && localStorage.isSupported) { localStorage.save({ key: local.browserStorageKey, value: local.getStatePartToSave(state), }); } if (session && sessionStorage.isSupported) { sessionStorage.save({ key: session.browserStorageKey, value: session.getStatePartToSave(state), }); } if (custom) { custom.saveToStorage(custom.getStatePartToSave(state)); } }