Skip to content

Instantly share code, notes, and snippets.

@mrtnbroder
Last active April 26, 2017 13:55
Show Gist options
  • Select an option

  • Save mrtnbroder/286e5f2e6a90b4fc5b5a13b06f01bc1e to your computer and use it in GitHub Desktop.

Select an option

Save mrtnbroder/286e5f2e6a90b4fc5b5a13b06f01bc1e to your computer and use it in GitHub Desktop.
Redux localStorage Middleware
import R from 'ramda'
const defaultConfig = (config = {}) => {
const {
localStorage: storage = { removeItem: R.F },
__APP_VERSION__: version = '',
} = __BROWSER__ ? window : {}
const namespace = 'my-cool-app'
const appName = `${namespace}.v${version}`
return {
appName,
blacklistActions: [/PENDING$/, /REJECTED$/],
blacklistReducers: ['modals'],
namespace,
storage,
version,
...config,
}
}
export const persist = (opts) => {
const {
blacklistActions,
blacklistReducers,
storage,
appName,
} = defaultConfig(opts)
const sanitize = R.compose(JSON.stringify, R.omit(blacklistReducers))
const blacklist = R.flip(R.none)(blacklistActions)
const passes = R.flip(R.test)
const validAction = R.pipe(passes, blacklist)
return R.curry((store, next, action) => {
next(action)
if (validAction(action.type)) {
storage[appName] = sanitize(store.getState())
}
})
}
export const rehydrate = (opts) => {
const { storage, appName, namespace } = defaultConfig(opts)
const exp = new RegExp(namespace, 'g')
const isCurrentVersion = R.equals(appName)
const gotOldData = R.both(R.test(exp), R.complement(isCurrentVersion))
const purge = R.bind(storage.removeItem, storage)
R.forEach(R.ifElse(gotOldData, purge, R.F), R.keys(storage))
return JSON.parse(storage[appName] || '{}')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment