Search code examples
reactjsuse-effect

Why my useEffect that tries to get blockchain data is looping infinitely and my async func still returns Promise pending


I am trying to use async await inside a useEffect hook getting some data from a testnet blockchain but I am getting 2 problems:

  1. The async function returns a Promise, why is that? Shouldn't async await automatically resolve the promise and give me the data? I tried to solve it with Promise.resolve but not working, it still tells me campaigns is a Promise in pending state.
  2. It enters in an infinite loop and I still do not get why.

Here is the code:

  useEffect(() => {
    const getCampaigns = async() => {
      const campaigns = await factory.methods.getDeployedCampaigns().call()
      return campaigns
    }
    const campaigns = getCampaigns();
    setCampaigns(Promise.resolve(campaigns));

    console.log('campaigns: ', campaigns);
  })

Solution

  • You have no dependencies array.

    useEffect(() => {
       const getCampaigns = async() => {
          const campaigns = await factory.methods.getDeployedCampaigns().call()
          return campaigns
       }
       
       const campaigns = getCampaigns();
       setCampaigns(Promise.resolve(campaigns));
       console.log('campaigns: ', campaigns);
    }, [])