Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uncaught SyntaxError: Unexpected token u in JSON at position 0 #66

Open
ocraml opened this issue Jul 1, 2022 · 1 comment
Open

Uncaught SyntaxError: Unexpected token u in JSON at position 0 #66

ocraml opened this issue Jul 1, 2022 · 1 comment

Comments

@ocraml
Copy link

ocraml commented Jul 1, 2022

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

@mateuspiresl
Copy link

mateuspiresl commented Aug 15, 2022

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);

  // ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants