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

157
Vistas
how to stop state from returning undefined?
  const [user,setuser] = useState()

 
  useEffect(()=> {
    try{
    

     const User = (jwt_decode(localStorage.getItem("token")))
     setuser(User)
     console.log(User)
  
      
 
      
      
      
    }catch(e){

    }
  },[])
   
   
   

 console.log(user)

console :undefined
VM7512:249 undefined
App.js:27 {username: 'john4', password: '####', iat: 1649430959}
App.js:42 {username: 'john4', password: '####', iat: 1649430959}
VM7512:249 [object Object]

why does the user Object give undefined first is there a way i cant prevent this? i need the console to only log the actual value and not undefined.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

const [user,setuser] = useState()

The default value for the state is determine by the argument you pass to useState. You aren't passing anything so it is implicitly undefined.

Pass it a value.

const [user,setuser] = useState("not undefined");

That said, you probably only want to deal with it after the useEffect hook has run. In which case you should generally handle the undefined state explicitly.

A typical example would be:

const [user,setuser] = useState()

useEffect(.....);

if (!user) {
    return <LoadingSpinner />
}

return <UserDetails user={user} />

And that said, your effect hook is running only once (when the component is mounted) and isn't asynchronous, so you could move the logic for it to a function you pass to useState.

That function will only run if the state hasn't been set yet, so you still get the benefit of not rerunning it on every render:

const [user, setuser] = useState(() => {
    try {
        const User = (jwt_decode(localStorage.getItem("token")))
        setuser(User)
        console.log(User)
    } catch (e) {

    }
});
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