1

I am using Alchemy API to handle fetching NFTs and their metadata in my platform. It has valuable methods, such as retrieving all issued NFTs of a collection or all owned NFTs of an address within a specified network.

However, I need to get the NFTs that a specific address owns from a target NFT collection. Is there a solution to this in Alchemy docs ( since I did not find it )? Or do I have to filter Alchemy's response by the Javascript filter( ) method?

This is the script I am using for this purpose.

  const [ nfts, setNfts ] = useState(null)


  const settings = {
    apiKey: 'Alchemy API Key', 
    network: Network.MATIC_MAINNET, 
  };

  const alchemy = new Alchemy(settings);

  useEffect(() => {
    fetchNfts()
  }, [])

  const fetchNfts = async () => {
    console.log("Fetching NFTs ...");
    const response = await alchemy.nft.getNftsForContract("0x220A95bdE3ffa364050FFe07b436869C08787eC8");
    setNfts(response.nfts);
  }

3 Answers 3

2

(1) Get all the NFTs of an address owned within a specific network by ( You have to do the network configuration earlier ):

await alchemy.nft.getNftsForOwner(address)

(2) Then store the response ( It's an object } in a state variable

(3) Within the return section of your component, try to map over the stored array (state variable ) and filter them out based on each NFT's contract address like:

{
    nfts.map((nft, i) => (
        <div key={i}>
            <img src={nft.image} className="rounded" />
            <div>      
                <p>Price - {nft.price} Matic</p>
            </div>
        </div>
    ))
}

Each nft ( from the array we received from Alchemy and stored in a stat variable ) has some valuable properties that you can use based on the needs of your project

1

I am not familiar with Alchemy's API, but you could definitely do this by building a subgraph for this, to index the data specific to your needs. And then query the data from a frontend like you would from Alchemy's API.

0

With this logic:

    const balance = await NFT.balanceOf(walletAddress);


    const getTokensId = async (recipient, index) => {
        try {
            const result = NFT.tokenOfOwnerByIndex(recipient, index);
            return result;
        } catch (error) {
            console.log(error, "the error for getTokensId");
        }
    };

You can get the balance and the tokenId owner of a specific contract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.