Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda