0

I am running into a problem where a for loop is running when a page is first loaded, but the array I am trying to fill remains empty until I do a "hot reload" by making some sort of adjustment in the code. My goal is to load this data into the array so I can display it on the webpage.

  const router = useRouter()
  const data = router.query
  const [tokenMeta, setTokenMeta] = useState('')
  const [tokenImage, setTokenImage] = useState('')
  const [recordList, setRecordList] = useState([])
  useEffect( async () => {  
  
    if(router.isReady) {
      const response = await web3.alchemy.getNftMetadata({
        contractAddress: ContractAddress,
        tokenId: data.tokenID
      }) 
      setTokenMeta(response.metadata)
      const image = await GetTokenImage(data.tokenID)
      setTokenImage(image) 

      for (let i = 0; i < 3; i++) {
        let record = await ReadRecord(data.tokenID, i)
        
        setRecordList(recordList => [...recordList, record])
        console.log("Record List: ", recordList)
        console.log("Counter: ", i)
      }
    }
  },[router.isReady])

recordList will log but be an empty array until the hot reload where it will properly fill with the information I need it to. I also had similar issues using a while loop. It is also important to note that tokenMeta and tokenImage fill just fine on the initial load.

Console

eljimm
  • 43
  • 5
  • Don’t think that async in useEffect is good idea, and before for loop you have to wrap it in await Promise.all – antokhio Sep 09 '22 at 20:43
  • 1
    @KonradLinkowski Yes it does, thank you. My code does seem to work correctly, it was just not updated in time when I was trying to log – eljimm Sep 09 '22 at 21:07

0 Answers0