Last active
February 26, 2024 15:29
-
-
Save no-stack-dub-sack/231477687452e6dfcf902e600ca083db to your computer and use it in GitHub Desktop.
Persist redux state to 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 { store } from './fileWhereStoreLives'; | |
// add this code in your app's entry point file to | |
// set localStorage when navigating away from app | |
window.onbeforeunload = function(e) { | |
const state = store.getState(); | |
localStorage.setItem( | |
'local-storage-key', | |
JSON.stringify(state.stateYouWantToPersist) | |
); | |
}; | |
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 { importedState } from './fileWhereStateLives'; | |
// define your reducer's initial state: | |
const initialState = { | |
...importedState; | |
}; | |
// define default state for each subsequent visit. | |
// if localStorage with this key exists, assign it | |
// to this variable, otherwise, use initialState. | |
const defaultState = JSON.parse( | |
localStorage.getItem('local-storage-key') | |
) || initialState; | |
// set defaultState of reducer to result of above operation | |
const reducer = (state = defaultState, action) => { | |
switch (action.type) { | |
case 'DO_SOMETHING_COOL': | |
return { | |
...state, | |
...action.newState | |
}; | |
default: | |
return state; | |
} | |
} | |
export default reducer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment