Reputation: 491
My State
const [isEnabled, setIsEnabled] = useState(false);
GetUser()
async function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
await Axios.get(URL+getTokenIdFromURL).then(function (response) {
setIsEnabled(response.data.enabled) /* Checks if updated value is true and updates state */
})
}
UseEffect()
useEffect(() => {
getUser();
return () => {
/* */
};
}, []);
Return
return (
<div className="emailVerificationWrapper">
{isEnabled ? <h1>true</h1> : <EmailVerificationFailed /> }
</div>
)
Return is rendered before the setIsEnabled
which causes the final result to be false
, but if i reload the website(or console log the state value), it is set to true
(as desired).
How can i make the
setIsEnabled
to update the state before my applications renders thereturn
?
Upvotes: 0
Views: 67
Reputation: 282140
useEffect is run, post your render return statement. You need to have a loading state to wait till the data is fetched
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
getUser();
return () => {
/* */
};
}, []);
function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
Axios.get(URL+getTokenIdFromURL).then(function (response) {
setIsLoading(false);
setIsEnabled(response.data.enabled)
})
}
if(isLoading) {
return <div>Loading...</div>
}
return (
<div className="emailVerificationWrapper">
{isEnabled ? <h1>true</h1> : <EmailVerificationFailed /> }
</div>
)
Upvotes: 1
Reputation: 570
useEffect(async () => {
await getUser();
return () => {
/* */
};
}, []);
Upvotes: 0
Reputation: 570
Please update like this:
async function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
const response = await Axios.get(URL+getTokenIdFromURL)
setIsEnabled(response.data.enabled) /* Checks if updated value is true and updates state */
}
Upvotes: 0