Search code examples
reactjsfetchmappinguse-effect

How correctly fetch and save data inside an array using useEffect


I am using React and asynchronously fetching data from the blockchain with useEffect. What I do not understand is that while the console.log inside the map function works and it prints the right data, supposedly it should save that data inside data array, but when I log data outside the map (meaning it should have finished to save the data) I get an array of undefined values. Code:

  useEffect(() => {
    const data = mainnet.Vaults.map((pool) => {
      const loadLendingData = async () => {
        const dataPool = await getPoolInfo(pool);
        console.log('dataPool', dataPool) //all good it prints everything
        return dataPool
      };
      loadLendingData();
     })
     console.log('data', data) //[undefined, undefined, undefined and so on]  
     setData(data)
  }, []);

Why is this happening? What am I doing wrong?

EDIT: I fixed the problem by storing data with useState for each loop in map. Code:

  useEffect(() => {
    mainnet.Vaults.map((pool) => {
      const loadLendingData = async () => {
        const dataPool = await getPoolInfo(pool);
        setLendingData((prevPool) => [...prevPool, dataPool])
      };
      loadLendingData();
     })
  }, []);

But still I'd like to understand why the first example didn't work.


Solution

  • I see that you are not returning anything from the map function, that's why the array has undefined elements outside the map function.

    return loadLendingData()
    

    This should solve the problem for you.