Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda