Created
September 8, 2016 18:19
-
-
Save goldhand/86a66836a2ebf7620112d04c8fe358a4 to your computer and use it in GitHub Desktop.
React redux local storage
This file contains hidden or 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 localforage from 'localforage'; | |
import throttle from 'lodash/throttle'; | |
const forageConfig = { | |
name: 'myproject', | |
storeName: 'myproject-data', | |
}; | |
const appStore = localforage.createInstance(forageConfig); | |
export const loadState = () => ( | |
appStore.getItem('state') | |
.then(state => { | |
if (state) { | |
return state; | |
} | |
return undefined; | |
}) | |
.catch(() => { | |
// TODO: handle err | |
return undefined; // combine reducers needs a value | |
}) | |
); | |
export const saveState = (state) => { | |
appStore.setItem('state', state) | |
.catch(() => { | |
// TODO: handle err | |
}); | |
}; | |
const SAVE_THROTTLE = 1000; | |
/** | |
* Save an array of redux stores as keys in local storage | |
* @param {Object} store - Redux store | |
* @returns {function} - save state function | |
*/ | |
export function saveReduxStore(store) { | |
/** | |
* @param {string[]} states - Array of store keys as strings | |
* @constructor | |
*/ | |
return (states) => { | |
store.subscribe(throttle(() => { | |
saveState({ | |
// list stores to save | |
...states.reduce((storeObj, state) => { | |
storeObj[state] = store.getState()[state]; | |
return storeObj; | |
}, {}), | |
}); | |
}, SAVE_THROTTLE)); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment