3

I'm trying to get all the NFTs in a collection that a wallet owns, but I only achieved get all the NFTs of a collection, or all the NFTs of a wallet (multi collections).

import { useConnection, useWallet } from "@solana/wallet-adapter-react"
import { Metaplex, walletAdapterIdentity } from "@metaplex-foundation/js"

...

const walletAdapter = useWallet()
const { connection } = useConnection()
const metaplex = Metaplex.make(connection).use(walletAdapterIdentity(walletAdapter))

// Get all NFTs of my collection
const candyMachine = await metaplex
   .candyMachinesV2()
   .findByAddress({ address: new PublicKey(candyMachineAddress) })

// Get all NFTs of wallet (My collection and others)
const walletNFTs = await metaplex
   .nfts()
   .findAllByOwner({ owner: wallet.publicKey })

Is this filter possible? I was exploring Metaplex SDK, but I didn't find this type of filter.

Thanks!

2 Answers 2

1

Try filtering for a collection address, something like the following

   // using metaplex SDK to fetch all NFTs of connected wallet
    const nfts = await metaplex
      .nfts()
      .findAllByOwner({ owner: wallet.publicKey })
     

    // filter for nfts in "collection"
    let nft = []
    for (let i = 0; i < nfts.length; i++) {
      if (nfts[i].collection?.address.toString() == collectionAddress.toString()) {
        nft.push(nfts[i])
      }
    }
1
  • Yes, this could work. But I wonder if there is a way to get this NFTs without a custom filter. If the user has hundreds of NFTs, I need to get all of them to show a few. I was finding a more performance way. It seems Metaplex doesn't have a method to this. Jan 14 at 21:48
0

This returns an array of Metadata object that has a collection field. You can filter the NFTs that match the collection you're looking for.

const walletNFTs = await metaplex
   .nfts()
   .findAllByOwner({ owner: wallet.publicKey })
1
  • As I said in the other comment, this way it works. However, it is not very performant. Jan 14 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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