Session Storage not being retrieved on mobile browser

丶灬走出姿态 提交于 2020-02-06 07:30:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!