Lee Alex
Lee Alex

Reputation: 171

Making a async function inside useEffect, and use await inside the while loop in the function, seems doesn't work

Did anyone meet some questions like me? I make an async function inside useEffect, and call it. In the async function, I have a while loop, and use await inside the while loop, but it seems like doesn't work, console.log(productsList.length) will print 0, and when I try to use productsList.map to return some components, also return nothing

useEffect(() => {
        async function callProduct(){
            let a=5
            while (a>0) {
                const item = await contract.getProduct(a)
                await setProductsList([...productsList,item]])
               a--
            }
        }
        callProduct()
        console.log(productsList.length)
    },[])

Upvotes: 0

Views: 1417

Answers (2)

Viet
Viet

Reputation: 12787

Because the new state only updates when the component re-render so you should put console.log inside useEffect with dependencies to check.

useEffect(() => {
    async function callProduct() {
        let a = 5;
        const newProductList = [];
        while (a > 0) {
            const item = await contract.getProduct(a);
            newProductList.push(item);
            a--;
        }

        setProductsList(newProductList);
    }
    callProduct();
}, []);

useEffect(() => {
    console.log(productsList.length)
}, [productsList])

Upvotes: 2

Christian Fritz
Christian Fritz

Reputation: 21364

All functions in JS return right away after processing each step, whether they are async or not. async functions just return a promise, but they still return without waiting for anything. So your console.log will execute right away showing the length of the product list. BTW, even if the setProductList had executed, the productList state variable would still be a the same as before because useState setters don't apply right away.

Just put your console.log outside of your useEffect. Once getProduct returns, it will set the variable and your component will refresh, printing the console.log at that point.

Upvotes: 2

Related Questions