Reputation: 113
Im trying to update my usestate funtion but im always getting 2 values , the initial state and updated state ,the reason why I cant get the proper values for my variables , how can I fix this? I only wanted the 2nd(updated value) on rerender
const userexist = JSON.parse(localStorage.getItem('userpersist'))
const [user,setUser]=useState(null)
useEffect(() => {
if (userexist){
const fetchComments=async()=>{
const response=await apiClient('/getuser');
setUser(response.data)
setfirstName(response.data.firstName)
setlastName(response.data.lastName)
}
fetchComments();
}else{
console.log('no user')
}
}, [])
useEffect(() => {
console.log(user)
}, [user])
the result of console log are
null
the response.data
Upvotes: 3
Views: 1149
Reputation: 1170
useEffect
will always run twice even if the dependencies array is empty. So in your case on the first render logs the value of the user on his initial state that's null and then renders again and shows you the new state.
Check this other SO answer for better explanation.
Upvotes: 2