I am developing a web app using React and here is what I am trying to do:
I wrote the below code. The problem is that there is apparently a time lag for the userinfo context value to be delivered to the component. So when using useEffect() hook, Profile.js will render twice when userinfo is not null.
Is there a way to fix this code so that it waits for 'userinfo' variable, and then call relevant APIs accordingly, not before?
Below is the code. Any advice? Thanks a lot in advance!
import React, {useEffect, useContext} from 'react';
import Userinfo from "../context/Userinfo";
function Profile(props) {
const {userinfo, setuserinfo}=useContext(Userinfo);
useEffect(()=>{
((userinfo==null)?
/*API call A (When user is not logged in) */ :
/*API call B (When user is logged in) */
)},[userinfo])
return (
(userinfo==null)?
/*Elements to render when user is not logged in) */ :
/*Elements to render when user is logged in) */
);
}
export default Profile;
The best solution here is to add a loading state in the context provider which is reset once the value is updated.
function Profile(props) {
const {userinfo, loading, setuserinfo}=useContext(Userinfo);
useEffect(()=>{
if(!loading) {
((userinfo==null)?
/*API call A (When user is not logged in) */ :
/*API call B (When user is logged in) */
)
}
)},[loading, userinfo])
if(loading) return <Loader />
return (
(userinfo==null)?
/*Elements to render when user is not logged in) */ :
/*Elements to render when user is logged in) */
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With