useEffect returning null

Asked

Viewed 42 times

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.

  • @Cmtecardeal, how can I use the await inside the useEffect? I’ve tried it here and nothing for now. I appreciate the reply!

  • @Cmtecardeal yes, remains null! :(

2 answers

1

The way you’re using the useEffect it will run only during the first rendering of your component, such as your list depends on an asynchronous call it will possess the initial value you assigned. if you want to see the values in your console.log recommend that you put off your useEffect, for example:

useEffect(() => {
        setName();
        handleTotals();        
    }, [])

console.log(list);

So once your call is finalized and the setList is called your component will render with the updated state, it is important you understand that the useEffect will not be executed during this second render.

  • I’ve tried this way too, remains null! :(

  • There is some more snippet of your code that you run a setList ?

  • I have placed in a repository of github: https://github.com/ThiagoxxLive/z1app/blob/master/src/screens/Dashboard/index.js

-1

async function loadTotals(){
   setName();
   // deve aguardar finalizar a requisição, tambem é possível utilizando o `.then`
   await handleTotals();        
   console.log(list);
}

useEffect(() => {
   loadTotals()    
}, [loadTotals])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.