Access sessionStorage at componentDidMount

2019-08-20 11:58发布

I was under the assumption that sessionStorage gets instantiated after a component has been mounted and one can access it through a componentDidMount call.

I am using this script to preserve my sessionStorage through different tabs:

(function() {     
  if (!sessionStorage.length) {
    // Ask other tabs for session storage
    localStorage.setItem('getSessionStorage', Date.now());
  };

  window.addEventListener('storage', function(event) {
    if (event.key == 'getSessionStorage') {
      // Some tab asked for the sessionStorage -> send it
      localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
      localStorage.removeItem('sessionStorage');
    } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
      // sessionStorage is empty -> fill it
      let data = JSON.parse(event.newValue);
      for (key in data) {
        sessionStorage.setItem(key, data[key]);
      }
      showSessionStorage();
    }
});

  window.onbeforeunload = function() {
    //sessionStorage.clear();
  };
})();

which seems to work as intended.

I am trying to access my sessionStorage through the componentDidMount method of the following (stripped down) component:

export default class Dashboard extends React.Component {
  componentDidMount() {
    console.log(window.sessionStorage.getItem('someData'));
  }

The above works as intended on the same tab.

When I open a new tab though, on the console I get null from the sessionStorage.
If I refresh the new tab, I get the correct someData value printed.

EDIT:

I did change my implementation to use a cookie in order to achieve my needs, but I am still interested in the problem and any potential solutions.

1条回答
贼婆χ
2楼-- · 2019-08-20 12:14

It is working as intended.

Session storage works for your current session. When you open a new tab you are creating a new session, that's why the initial data is null.

Use localStorage to persist data within tabs.

I don't know your use case but start with switching out sessionStorage and localStorage.

Save the normal things on sessionStorage. Persist on localStorage

查看更多
登录 后发表回答