Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!