Home > Back-end >  Why is useEffect running once?
Why is useEffect running once?

Time:08-24

When I try to test this code portion by running useEffect on the info state, I notice that the info state runs 1 time less than it should be. Can I know why? data.length = 2

const fetchData = async function (contractAddress) {
        setContractAddress(contractAddress)
        const loan = await readLoanAmount({"address": contractAddress});
        setLoanAmount(loan)
        const collected = await readCollectedAmount({"address": contractAddress});
        setCollectedAmount(collected);
        setInfo([...info, {"contractAddress":contractAddress,"loanAmount": loanAmount, "collectedAmount":collectedAmount}])
    }
    

    useEffect(() => {
        checkWalletIsConnected();
        fetch('http://localhost:5000/loanContract/getloanContracts').then((response) => response.json()).then((data) => {
            for(let i =0 ; i< data.length; i  ){
                let ca = data[i]["contractAddress"];
                fetchData(ca);
            }
        }).catch((err) => {
            console.log(err.message);
        });
    }, []); 

CodePudding user response:

From React Beta Docs

Whenever we supply an empty array to the second argument of useEffect, the effect runs only once after render. That is by definition how React built the hook.

Link to useEffect expalaination in React Docs Beta: https://beta.reactjs.org/learn/synchronizing-with-effects

CodePudding user response:

Did you mean for loop inside your useEffect is running once only instead of twice (as it should for data.length = 2)?

It could be due to the way you have used setInfo setter. Instead of getting the info value directly, do the following:

setInfo(prevInfo => {
    return [
        ...prevInfo,
        {
            "contractAddress":contractAddress,
            "loanAmount": loanAmount,
            "collectedAmount":collectedAmount
        }
    ];
});

Receiving prevInfo this way makes sure you have the latest value of info especially when dealing with synchronous consecutive calls to the setter function of useState. This might solve the issue you're facing...

  • Related