Skip to content

Commit fd3f26c

Browse files
authored
Merge pull request #253 from hackdays-io/bugfix/issue246
metadata parallel fetch
2 parents 90538d8 + e64eaba commit fd3f26c

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

frontend/src/hooks/useMintNFT.ts

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,15 @@ export const useGetOwnedNftIdsByAddress = (address?: string) => {
5555
useEffect(() => {
5656
const fetch = async () => {
5757
if (!address || isLoading) return;
58-
const _ids: number[] = [];
5958
const balance = await mintNFTContract?.call("balanceOf", [address]);
60-
for (let index = 0; index < balance.toNumber(); index++) {
61-
const tokenId = await mintNFTContract?.call("tokenOfOwnerByIndex", [
62-
address,
63-
index,
64-
]);
65-
_ids.push(tokenId.toNumber());
66-
}
67-
setIds(_ids);
59+
const tokenIdsPromise = Array(balance.toNumber())
60+
.fill("")
61+
.map((_, index) => {
62+
return mintNFTContract?.call("tokenOfOwnerByIndex", [address, index]);
63+
});
64+
const tokenIds = await Promise.all(tokenIdsPromise);
65+
66+
setIds(tokenIds.map((id) => id.toNumber()));
6867
};
6968
fetch();
7069
}, [address, isLoading]);
@@ -146,18 +145,29 @@ export const useGetOwnedNFTByAddress = (address?: string) => {
146145

147146
const fetch = async () => {
148147
setIsLoading(true);
149-
const _nfts: any[] = [];
150-
for (const id of ids) {
151-
try {
148+
149+
const tokenURIPromises = ids.map((id) => {
150+
const getTokenURI = async (id: number) => {
152151
const tokenURI = await mintNFTContract?.call("tokenURI", [id]);
153-
const { data: metaData } = await axios.get(ipfs2http(tokenURI));
154-
_nfts.push({ ...metaData, tokenId: id });
155-
} catch (error) {
156-
console.log(error);
157-
continue;
158-
}
159-
}
160-
setNfts(_nfts);
152+
return { tokenURI, tokenId: id };
153+
};
154+
return getTokenURI(id);
155+
});
156+
const tokenURIs = await Promise.all(tokenURIPromises);
157+
158+
const metaDataPromises = tokenURIs.map(({ tokenURI, tokenId }) => {
159+
const getMetaData = async (tokenURI: string, tokenId: number) => {
160+
try {
161+
const { data: metaData } = await axios.get(ipfs2http(tokenURI));
162+
return { ...metaData, tokenId };
163+
} catch (error) {
164+
console.log(error);
165+
}
166+
};
167+
return getMetaData(tokenURI, tokenId);
168+
});
169+
const _nfts = await Promise.all(metaDataPromises);
170+
setNfts(_nfts.filter((nft) => nft));
161171
setIsLoading(false);
162172
};
163173

0 commit comments

Comments
 (0)