I have this code here:
function Homepage() {
const [name,setName] = useState('');
const [followers,setFollower] = useState('');
const [about,setAbout] = useState('');
useEffect(() => {
const fetchData = async () => {
const data = await loadhomepagescript();
console.log('User Name:', data.user_name);
console.log('About:', data.about);
console.log('Followers:', data.followers);
setName(data.user_name);
setFollower(data.about);
setAbout(data.followers);
};
fetchData();
}, []);
return (
<View style={styles.homepage}>
<View style={styles.uinfo}>
<Text style={{fontWeight:'bold', textAlign: 'left'}}>{name}</Text>
<Text style={{fontWeight:'bold', textAlign: 'left'}}>{followers}</Text>
<Text style={{fontWeight:'bold', textAlign: 'left'}}>{about}</Text>
</View>
</View>
);
}
For some reason even though the data.user_name
, data.about
and data.followers
console.log
right I can’t pass them to my <Text>
elements. Why’s that?
I tried moving the useEffect
and also moving the return of the views, but nothing worked
2
Answers
The issue could be happened due to the order of execution. Since
useEffect
is asynchronous, it might take some time to fetch the data.Therefore, if the component renders before the data is available, the initial empty state values will be displayed.
You can conditionally render the component only when the data is available like below.
in my opinion stop using
useEffect
anymore and usereact-query
instead to handle fetching data properly something like that:if you need to use the
useEffect
hook you need to pass thatdata
that comes from theloadhomepagescript
function as a dependency in theuseEffect
array dependencies and be careful because it is an object so you need to memorize thatdata
usinguseMemo
hook