Skip to content

Instantly share code, notes, and snippets.

@tfiechowski
Last active April 2, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfiechowski/8b1ae672df92e3a173618046fa27805c to your computer and use it in GitHub Desktop.
Save tfiechowski/8b1ae672df92e3a173618046fa27805c to your computer and use it in GitHub Desktop.
WIP: Redux root reducer caching state in local storage
import { CHANGE_TEAM } from 'modules/Team/Team';
const getCurrentTeamId = () => window.localStorage.getItem('current-team');
const readTeamData = teamId => {
const newStateData = window.localStorage.getItem(`team-data-${teamId}`);
if (newStateData) {
return JSON.parse(newStateData);
}
return null;
};
const saveTeamData = (state, teamId) => {
window.localStorage.setItem(`team-data-${teamId}`, JSON.stringify(state));
window.localStorage.setItem(`current-team`, teamId);
};
const rootReducer = appReducer => (state, action) => {
const currentTeamId = getCurrentTeamId();
if (action.type === '@@INIT' && currentTeamId) {
state = readTeamData(currentTeamId);
} else if (action.type === CHANGE_TEAM) {
const teamId = action.payload.id;
saveTeamData(state, teamId);
const newStateData = window.localStorage.getItem(`team-data-${teamId}`);
if (newStateData) {
state = JSON.parse(newStateData);
}
}
return appReducer(state, action);
};
// window.addEventListener('unload', () => {
// const currentTeamId = getCurrentTeamId();
// const state = window.__store__.getState();
// saveTeamData(state, currentTeamId);
// });
export default rootReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment