Created
January 8, 2016 23:24
-
-
Save HenrikJoreteg/8e02b6e5a74a98f04489 to your computer and use it in GitHub Desktop.
Example redux middleware
This file contains 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 { STAR_PERSON, MET_PERSON, UPDATE_NOTES, SET_URL } from '../constants/action-types' | |
import { LS_KEY } from '../constants/localstorage-keys' | |
import tryit from 'tryit' | |
import debounce from 'lodash.debounce' | |
const userPreferenceActions = [STAR_PERSON, MET_PERSON, UPDATE_NOTES] | |
function writeToLocalStorage (getState) { | |
let data = { | |
starred: {}, | |
met: {}, | |
notes: {} | |
} | |
getState().personData.originalPersons.forEach(person => { | |
if (person.notes) data.notes[person.slug] = person.notes | |
if (person.starred) data.starred[person.slug] = true | |
if (person.met) data.met[person.slug] = true | |
}) | |
window.localStorage[LS_KEY] = JSON.stringify(data) | |
} | |
const debouncedWrite = debounce(writeToLocalStorage, 300) | |
export default function persistMiddleware (getState) { | |
return next => | |
action => { | |
next(action) | |
// write person data changes to localStorage | |
if (action && userPreferenceActions.indexOf(action.type) !== -1) { | |
debouncedWrite(getState) | |
} | |
// write last url to localStorage | |
if (action.type === SET_URL) { | |
window.localStorage.lastUrl = action.text | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment