1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-23 02:10:12 +01:00
metamask-extension/ui/hooks/useNftsCollections.js
David Walsh e895ff33f9
NFTs: Use Unknown Collection instead of first NFT name (#18388)
* NFTs: Use Unknown Collection instead of first NFT name

* Use localization in hook

* Get localization for previously owned

* Fix tests

---------

Co-authored-by: Dan Miller <danjm.com@gmail.com>
2023-03-31 06:41:07 -02:30

81 lines
2.6 KiB
JavaScript

import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { isEqual } from 'lodash';
import { getNfts, getNftContracts } from '../ducks/metamask/metamask';
import { getCurrentChainId, getSelectedAddress } from '../selectors';
import { usePrevious } from './usePrevious';
import { useI18nContext } from './useI18nContext';
export function useNftsCollections() {
const t = useI18nContext();
const previouslyOwnedText = t('nftsPreviouslyOwned');
const unknownCollectionText = t('unknownCollection');
const [collections, setCollections] = useState({});
const [previouslyOwnedCollection, setPreviouslyOwnedCollection] = useState({
collectionName: previouslyOwnedText,
nfts: [],
});
const nfts = useSelector(getNfts);
const [nftsLoading, setNftsLoading] = useState(() => nfts?.length >= 0);
const selectedAddress = useSelector(getSelectedAddress);
const chainId = useSelector(getCurrentChainId);
const nftContracts = useSelector(getNftContracts);
const prevNfts = usePrevious(nfts);
const prevChainId = usePrevious(chainId);
const prevSelectedAddress = usePrevious(selectedAddress);
useEffect(() => {
const getCollections = () => {
setNftsLoading(true);
if (selectedAddress === undefined || chainId === undefined) {
return;
}
const newCollections = {};
const newPreviouslyOwnedCollections = {
collectionName: previouslyOwnedText,
nfts: [],
};
nfts.forEach((nft) => {
if (nft?.isCurrentlyOwned === false) {
newPreviouslyOwnedCollections.nfts.push(nft);
} else if (newCollections[nft.address]) {
newCollections[nft.address].nfts.push(nft);
} else {
const collectionContract = nftContracts.find(
({ address }) => address === nft.address,
);
newCollections[nft.address] = {
collectionName: collectionContract?.name || unknownCollectionText,
collectionImage: collectionContract?.logo || nft.image,
nfts: [nft],
};
}
});
setCollections(newCollections);
setPreviouslyOwnedCollection(newPreviouslyOwnedCollections);
setNftsLoading(false);
};
if (
!isEqual(prevNfts, nfts) ||
!isEqual(prevSelectedAddress, selectedAddress) ||
!isEqual(prevChainId, chainId)
) {
getCollections();
}
}, [
nfts,
prevNfts,
nftContracts,
setNftsLoading,
chainId,
prevChainId,
selectedAddress,
prevSelectedAddress,
]);
return { nftsLoading, collections, previouslyOwnedCollection };
}