问题
I have a create-react-app and I'm storage some state inside of sessionStorage to persist some redux state during the user's session.
Everything works fine in Desktop browsers but while debugging on a mobile device inside of Safari or Chrome the state isn't be retrieved on refresh. This causes errors since the state is no longer there.
Any idea why this would only happen on a mobile browser?
This is how I'm saving and retrieving the state with sessionStorage:
export function saveToLocalStorage(state: AppState) {
const hasUserProfileId =
state.system.profile.id && state.system.profile.id !== '';
try {
if (hasUserProfileId) {
const serializedState = JSON.stringify(state);
sessionStorage.setItem('state', serializedState);
}
} catch (error) {
console.log('Error saving state to local storage');
}
}
function loadFromLocalStorage() {
console.log('loadFromLocalStorage - 1');
try {
const serializedState = sessionStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (error) {
console.log('Error loading state from local storage');
return undefined;
}
}
its null when doing const serializedState = sessionStorage.getItem('state');
so it returns undefined
if (serializedState === null) {
return undefined;
}
回答1:
I was using beforeunload
event listener to save the state on refresh. This event handler wasn't supported for mobile browsers. Replacing it with unload
worked.
window.addEventListener('unload', () => {
saveToLocalStorage(store.getState());
});
来源:https://stackoverflow.com/questions/59514333/session-storage-not-being-retrieved-on-mobile-browser