Reputation: 11030
I'm currently using react redux with a wizard form. I've now run into the issue where I need to persist the data in the form or just refresh the data but let the user know.
Currently everything is stored in multiple redux states.
Is there a way to detect a "refresh" event by a user?I will most likely use local storage, but I'm curious of the first option and wondering if it's possible.
Upvotes: 3
Views: 16096
Reputation: 6928
If you want to detect a refresh event, It has nothing to do with React, instead use plain Javascript event handler called window.onbeforeunload
window.onbeforeunload = (e) => {
// I'm about to refresh! do something...
};
However I don't think it's the proper approach to store Redux store, instead you can do something like:
// load state from localStorage
const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined; // reducer will return Redux state, as localstorage is null.
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
const saveToLocalStorage = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// ignore error
}
};
store.subscribe(() => {
saveToLocalStorage(store.getState()); // save current state to localstorage.
});
Upvotes: 5