Home > Net >  Unexpected token u in JSON at position 0 in redux
Unexpected token u in JSON at position 0 in redux

Time:06-06

I'm creating a user register and I'm using the redux toolkit. When the user details are not in the local storage I'm setting it to null. But since the beginning the user is undefined, it should assign it a null value but I'm getting this error:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

due to this code:

// Get user from localStorage
const user = JSON.parse(localStorage.getItem("user"));

//initials state
const initialState = {
  user: user ? user : null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

How should I write it or what I'm doing wrong? I understand the value undefined is what is being stringified.

CodePudding user response:

Any time you see Unexpected token u in JSON at position 0, it's almost certainly because you're trying to pass undefined to JSON.parse. JS will automatically convert it to the string "undefined", which is not valid JSON.

Something like JSON.parse(localStorage.getItem("user") || "null") should do the trick. This will pass the string "null" (which is valid JSON) instead if localStorage.getItem("user") returns anything "falsy".

This also means you don't need the user ? user : null later on - you can replace that with just user.

CodePudding user response:

Clearing local storage solved the issue.Thank you

  • Related