Sunday 14 March 2021

Why is localStorage sometimes null in MacOS/iOS devices right after availability check?

I am experiencing a problem, which is not very frequent but still occurs on a regular basis, in a web application which makes use of local storage.

The problem is only occurring in iOS/MacOS devices, regardless of browser, and the error that is being logged is the following:

TypeError: 'null' is not an object (evaluating 'localStorage.getItem')

Here's how the code works; there is a function (isLocalStorageSupported) that checks if local storage is supported, and there is another function (getLocalData) that uses it before trying to get data from the storage.

The error is thrown after the check for local storage completes by returning true, but the next line inexplicably (?) throws when trying to get a key from local storage, as the storage variable at that stage seems to be null.

It's unclear to me how this can happen, hence my question.

// The function that checks availability
const isLocalStorageSupported = (() => {
  let localStorageSupported = null;

  return () => {
    if (localStorageSupported !== null) {
      return localStorageSupported;
    }

    try {
      localStorage.setItem('check', 'check');
      localStorage.getItem('check');
      localStorage.removeItem('check');

      localStorageSupported = true;
    } catch (error) {
      localStorageSupported = false;
      console.error('localStorage not supported');
    }

    return localStorageSupported;
  };
})();

const getLocalData = (key) => {
  if (isLocalStorageSupported()) { // This check is successful

    let data = localStorage.getItem(key); // This line throws a TypeError!

    if (!data) {
      return;
    }

    return data;
  }
};


from Why is localStorage sometimes null in MacOS/iOS devices right after availability check?

No comments:

Post a Comment