简体   繁体   中英

array value not showing length, but when i open so the element is exist

array value not showing length, but when i open so the element is exist. but length and some other functions of array not working... """const getingLikedNft = async () => { setMyNftLoading(true); const res = await axios.get( ${BACKEND_URL}views_and_likes ); console.log("resshan", res); // let likedNft = []; var myLikedNft = new Array();

res?.data.forEach((element) => {
  // console.log("xshan", element);
  if (element?.likedAccounts.length > 0) {
    element?.likedAccounts.forEach(async (elem) => {
      if (elem?.toLowerCase() == user?.address?.toLowerCase()) {
        console.log("resshan_elem", element);
        try {
          let res = await axios.post(`${BACKEND_URL}single-nft`, {
            tokenId: element.tokenId,
            tokenAddr: element.tokenAddr,
          });
          console.log("reslikedNFT", res.data);
          // const uri = await contracts?.closedSeaNft?.methods
          //   .tokenURI(element.tokenId)
          //   .call();
          // const res = await axios.get(uri);
          var nftData = {
            description: res?.data?.metadata?.description,
            image: res?.data?.metadata?.imageUrl,
            title: res?.data?.metadata?.name,
            url: `/asset/${res?.data?.tokenAddr}/${res?.data?.tokenId}`,
          };
          console.log("reslikedN22FT2324232", Array.prototype.nftData);
          myLikedNft = [...myLikedNft, nftData];
          // myLikedNft.push({
          //   description: nftData.description,
          //   image: nftData.imageUrl,
          //   title: nftData.name,
          //   url: `/asset/${res?.data?.tokenAddr}/${res?.data?.tokenId}`,
          // });
        } catch (err) {
          console.log("element?.likedAccounts [err]", err);
        }
        // likedNft.push(element);
        // console.log("elem", elem);
      }
    });
  }
});
console.log("reslikedNFT2321312341312dasd", myLikedNft);
setMyLikesCollection(myLikedNft);
setTimeout(() => {
  setMyNftLoading(false);
}, 2000);

};"""

you can see it is showing empty array. 在此处输入图像描述

but when i open this so the element is exists.

在此处输入图像描述

how can i solve this kindly help...

You are making an async call for every iteration in the forEach loop. But the execution of the forEach will finish before you get a response for each of your async calls.

When you print the myLikedNft to the console, at the time of printing, the array has no data, because the async calls have not resolved. But when you expand them in the console, it gives you the latest value of the expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM