I am trying to fetch all nfts from different contracts using THIRDWEB. First I am fetching the contract addresses from sanity (which works perfectly fine) and then I am trying to fetch the nfts (you do it by using the useNFTCollection hook and then use the function getOwned).
Although the array that i receive (dataArray) i can see the elements of it (all the NFTs) but I cannot access any of the elements in the array (it always returns undefined) and i cannot access the length of the array.
Whereas if i try to grab the length of this array it just returns undefined.
The code:
import React, { useState, useEffect } from "react";
import Header from "../../components/Header/Header";
import UserImages from "../../components/Profile/UserImages";
import UserInfo from "../../components/Profile/UserInfo";
import { client } from "../../lib/sanityClient";
import { useNFTCollection } from "@thirdweb-dev/react";
import { useRouter } from "next/router";
export async function getServerSideProps({}) {
const query = `*[_type == "marketItems"] {
contractAddress,
}`;
const data = await client.fetch(query);
return {
props: {
data,
},
};
}
function profile({ data }) {
const [nfts, setNfts] = useState({});
const router = useRouter();
const { wallet } = router.query;
let dataArray = [];
if (data[0] !== undefined) {
if (dataArray === undefined || dataArray.length < 1) {
dataArray = [];
}
for (let i = 0; i < data.length; i++) {
const collection = useNFTCollection(data[i].contractAddress);
async function getNfts() {
if (collection !== undefined) {
await collection.getOwned(wallet).then((res) => {
Promise.all(res).then((values) => {
for (let i = 0; i < values.length; i++) {
dataArray.push(values[i]);
}
});
});
}
}
getNfts();
}
console.log(dataArray);
}
return (
<div>
<Header />
<UserImages />
<UserInfo />
</div>
);
}
export default profile;
How can i access the content of dataArray? And how can i assign it to any state variable? Note that I am using this loop this way because useNFTCollection is a Hook, and it does not allow me to use it in any useEffect or useMemo.
Oh and I am using nextJS in this example.