undefined" is not valid JSON

Viewed 42

it keeps returning undefined" is not valid JSON all the time

here is my code:

function App() {

  const [ user, setLoginUser] = useState({});

  useEffect(() => {
    setLoginUser(JSON.parse(localStorage.getItem("users")))
  }, [])

  const updateUser = (user) => {
    localStorage.setItem("users", JSON.stringify(user))
    setLoginUser(user)
  }

  return 
1 Answers

That's because "undefined" is not valid JSON

What you need to do is first check the value exists, then you can start working with it. As it is, when the component mounts, you're trying to JSON.parse something that may or may not exist.

if(localStorage.getItem("users")){your code here}

Is probably sufficient.

I'm guessing since you're a new user here you haven't spent that much time with JavaScript, you'll get used to this error and checking that something isn't null/undefined before attempting to manipulate it in some way.

Related