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

164
Visualizações
How can I fix the error How To Fix Unexpected token u in JSON at position 0

I have an error coming from my user reducer code. This is what i have done.

export const userReducer = (
  state = localStorage.getItem('user') !== undefined
    ? JSON.parse(localStorage.getItem('user'))
    : null,
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

I don't know if i'm declaring the state very well. I feel thats where the issue is coming from.

I hve tried to declare my state as

export const userReducer = (
  state = localStorage.getItem('user') 
  ? JSON.parse(localStorage.getItem('user')) 
  : null, 
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

I still get same error and my page does't load. It renders a blank screen, with the error in the console.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's a "safe" JSON parser, that handles a lot of funky/broken/bad/corrupt JSON:

function jparse(str) { 
    var result = null; 
    try { 
        result = JSON.parse(str) 
    } catch (e) {
        // ignore
    } 
    if (!result) {
        try {
            result = Function('return (' + str + ")")();
        } catch(e){
            // ignore
        }
    }
    return result;
}

console.log( jparse(null) );            // null
console.log( jparse('{bob:"er"}') );    // {bob: 'er'}
console.log( jparse('{\'bob\':"er"}') );// {bob: 'er'}
console.log( jparse('{bob:}') );        // null
console.log( jparse(0) );               // 0
console.log( jparse(false) );           // false
console.log( jparse(undefined) );       // undefined
about 4 years ago · Juan Pablo Isaza 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