Search code examples
javascriptreactjsfetchuse-effect

Why do I get an array of promises when getting data from the blockchain with useEffect?


I am using React and getting data from the blockchain using useEffect, but the problem is that after I mapped data and put it inside lendingData array, when logged it returns an array of promises. Code:

   const data = mainnet.Vaults.map((pool) => {
      const loadLendingData = async () => {
        const dataPool = await getPoolInfo(pool);
        // setLendingData((prevPool) => [...prevPool, dataPool]);
        return dataPool
      };
      return loadLendingData();
    });
    setLendingData(data)
    setLoading(false);
  }

Why am I getting the promises if I have used await when pulling the data?


Solution

  • It looks like you should be using map to create an array of promises that you can then await with Promise.all.

    const promises = mainnet.Vaults.map(pool => getPoolInfo(pool));
    
    const data = await Promise.all(promises);
    
    setLendingData(data);