Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at ./src/context/AuthContext.js

i was developing a booking app using MERN STACK ,can you please help me in this error

So the error comes in this part of Code in AuthContext.js file

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  loading: false,
  error: null,
}

I used the useEffect

export const AuthContextProvider=({children})=>{
  const [state,dispatch]=useReducer(AuthReducer,INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user",JSON.stringify(state.user))
  },[state.user]);

and the error which comes

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at ./src/context/AuthContext.js

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

localStorage.get returns undefined which cannot be parsed by JSON.parse. I usually use a function like this which catches the error and returns the value itself as a fallback.

function parse(value){
   try {
      return JSON.parse(value)
   } catch(_) {
      return value
   }
}
about 4 years ago · Santiago Gelvez Report

0

Error message indicates that issue is within JSON.parse which is used in INITIAL_STATE.

You can add guard, something like this:

const userLs = localStorage.getItem("user");
const INITIAL_STATE={
  user: userLs ? JSON.parse(userLs) : null,
  loading:false,
  error:null,
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!