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