Skip to content

Instantly share code, notes, and snippets.

@no-stack-dub-sack
Last active February 26, 2024 15:29
Show Gist options
  • Save no-stack-dub-sack/231477687452e6dfcf902e600ca083db to your computer and use it in GitHub Desktop.
Save no-stack-dub-sack/231477687452e6dfcf902e600ca083db to your computer and use it in GitHub Desktop.
Persist redux state to local storage
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)
);
};
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