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

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

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 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