Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Last active August 4, 2019 20:11
Show Gist options
  • Save bvaughn/118db0ab9d2db99cedbce9d3e124c178 to your computer and use it in GitHub Desktop.
Save bvaughn/118db0ab9d2db99cedbce9d3e124c178 to your computer and use it in GitHub Desktop.
Redux + localStorage
/** @flow */
import Immutable from 'immutable'
import { createSelector } from 'reselect'
const LOCAL_STORAGE_KEY = 'LocalStorageModule'
const ACTION_TYPES = {
REMOVE: 'REMOVE_ACTION',
SET: 'SET_ACTION'
}
// Module reducer
export function reducer (
state = deserialize(),
action: Object
): Immutable.Collection {
let key, nextState, value
switch (action.type) {
case ACTION_TYPES.REMOVE:
({ key } = action.payload)
nextState = state.remove(key)
serialize(nextState)
return nextState
case ACTION_TYPES.SET:
({ key, value } = action.payload)
nextState = state.set(key, value)
serialize(nextState)
return nextState
}
return state
}
// Memoized selector to access the main localStorage object
function localStorageState (state) {
return state.localStorage
}
// Memoized selector to access a named entry
export function get (key: string) {
return createSelector(
[localStorageState],
(localStorageState) => localStorageState.get(key)
)
}
// Action-creator to delete an entry from localStorage
export function remove (key: string): Object {
return {
type: ACTION_TYPES.REMOVE,
payload: {
key
}
}
}
// Action-creator to add/update an entry in localStorage
export function set (key: string, value): Object {
return {
type: ACTION_TYPES.SET,
payload: {
key,
value
}
}
}
// Hydrate Redux state based on most recently persisted values
function deserialize (): Immutable.Collection {
return Immutable.Map(
JSON.parse(
localStorage.getItem(LOCAL_STORAGE_KEY)
)
)
}
// Save current Redux state to localStorage
function serialize (state: Immutable.Collection) {
const serialized = JSON.stringify(state.toJS())
localStorage.setItem(LOCAL_STORAGE_KEY, serialized)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment