Last active
April 2, 2018 09:52
-
-
Save tfiechowski/8b1ae672df92e3a173618046fa27805c to your computer and use it in GitHub Desktop.
WIP: Redux root reducer caching state in 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 { 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