Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v5 compat #17

Merged
merged 2 commits into from
Dec 9, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 43 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,51 @@
var constants = require('redux-persist/constants')
var KEY_PREFIX = constants.KEY_PREFIX
// @flow
import { KEY_PREFIX, REHYDRATE } from 'redux-persist/lib/constants'
import type { PersistConfig } from 'redux-persist/es/types'
import type { Store } from 'redux'

module.exports = function(persistor, config){
var config = config || {}
var blacklist = config.blacklist || false
var whitelist = config.whitelist || false
var keyPrefix = config.keyPrefix || KEY_PREFIX
type CrosstabConfig = {
blacklist?: ?Array<string>,
keyPrefix?: ?string,
whitelist?: ?Array<string>,
}

module.exports = function (store: Store, persistConfig: PersistConfig, crosstabConfig: CrosstabConfig = {}) {
const blacklist: ?Array<string> = crosstabConfig.blacklist || null
const whitelist: ?Array<string> = crosstabConfig.whitelist || null
const keyPrefix: string = crosstabConfig.keyPrefix || KEY_PREFIX

const { key }: { key: string } = persistConfig

window.addEventListener('storage', handleStorageEvent, false)

function handleStorageEvent(e){
if(e.key && e.key.indexOf(keyPrefix) === 0){
var keyspace = e.key.substr(keyPrefix.length)
if(whitelist && whitelist.indexOf(keyspace) === -1){ return }
if(blacklist && blacklist.indexOf(keyspace) !== -1){ return }
if(e.oldValue === e.newValue){ return }
function handleStorageEvent (e) {
if (e.key && e.key.indexOf(keyPrefix) === 0) {
if (e.oldValue === e.newValue) {
return
}

const statePartial: { [string]: string } = JSON.parse(e.newValue)

/* eslint-disable flowtype/no-weak-types */
const state: Object = Object.keys(statePartial).reduce((state, reducerKey) => {
/* eslint-enable flowtype/no-weak-types */
if (whitelist && whitelist.indexOf(reducerKey) === -1) {
return state
}
if (blacklist && blacklist.indexOf(reducerKey) !== -1) {
return state
}

state[reducerKey] = JSON.parse(statePartial[reducerKey])

return state
}, {})

var statePartial = {}
statePartial[keyspace] = e.newValue
persistor.rehydrate(statePartial, {serial: true})
store.dispatch({
key,
payload: state,
type: REHYDRATE,
})
}
}
}