1
I’m starting with React Native, but I’m having trouble getting a list when loading the screen using useEffect
, every time you start the screen the first time, setList
returns empty, and when I click the refresh button, returns the data normally.
Can anyone explain to me why this happens? I looked at the documentation of useEffect
and actually the first time it is called, returns null, but I did not understand why in my call it does not return the API data.
Noting that when I click on the "refresh" button, the data returns normally.
const [list, setList] = useState([]);
const handleTotals = async () => {
setLoading(true);
setList([]);
let res = await Api.getOrderTotals();
if(res.data) {
setList(res.data);
}
setLoading(false);
}
useEffect(() => {
setName();
handleTotals();
console.log(list); //Retorna nulo
}, [])
handleTotals
is an asynchronous function, you have to wait for it to be completed to give a console.– Cmte Cardeal
@Cmtecardeal, how can I use the await inside the useEffect? I’ve tried it here and nothing for now. I appreciate the reply!
– Thiago Marcondes
@Cmtecardeal yes, remains null! :(
– Thiago Marcondes