use-persisted-state icon indicating copy to clipboard operation
use-persisted-state copied to clipboard

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Open ocraml opened this issue 2 years ago • 1 comments

I had the issue that the persisted value got set to undefined in the local storage. Debugging in chrome showed the key in the localStorage listed, but with value undefined set. Note that the value was set undefined, not to the string "undefined" For some unknown reason this ends to the json object beeing the string "undefined". Therefore line 6 of createStorage.js fails to catch it and it tries to parse the string 'undefined' as json. What leads to the error. Is: return json === null || typeof json === "undefined" ? ... Fix: return json === null || json === 'undefined' || typeof json === "undefined" ? ...

Environment: Chrome, windows 10, Visual Code, React

ocraml avatar Jul 01 '22 12:07 ocraml

Same here. Some users got undefined for some reason and it is causing crashes now. I was trying to find a way to handle the error using the library itself but I'm not sure if that is possible. I had to make a work around to validate the storage item before using the library hook. It validates only on component mounting.

function checkLocalStorageItem(key) {
  const value = localStorage.getItem(key);

  if (isNil(value)) {
    return true;
  }

  try {
    JSON.parse(value);
    return true;
  } catch (error) {
    return false;
  }
}

function useLocalStorageValidation(key) {
  const safeCheck = useRef(false);

  if (!safeCheck.current) {
    safeCheck.current = true;

    if (!checkLocalStorageItem(key)) {
      localStorage.removeItem(LOCAL_STORAGE_KEY);
    }
  }
}

// Using...

const usePersistedState = createPersistedState(LOCAL_STORAGE_KEY);

function MyComponent() {
  useLocalStorageValidation(LOCAL_STORAGE_KEY);
  
  const [storage, setStorage] = usePersistedState(DEFAULT_VALUE);

  // ...
}

mateuspiresl avatar Aug 15 '22 19:08 mateuspiresl