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

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

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