jumar
jumar

Reputation: 309

How to display Metaplex NFT in React using @metaplex/js and programs.metadata.Metadata

I am trying to run this 'getting started' example from the docs. However I think there's been a change and programs.metadata.Metadata (shown there) no longer works.

https://docs.metaplex.com/sdk/js/getting-started

They suggest this:

import { Connection, programs } from '@metaplex/js';

const connection = new Connection('devnet');
const tokenPublicKey = 'Gz3vYbpsB2agTsAwedtvtTkQ1CG9vsioqLW3r9ecNpvZ';

const run = async () => {
  try {
    const ownedMetadata = await programs.metadata.Metadata.load(connection, tokenPublicKey);
    console.log(ownedMetadata);
  } catch {
    console.log('Failed to fetch metadata');
  }
};

run();

I have this in my React app:

import { Connection, programs } from '@metaplex/js';

const connection = new Connection('devnet');
const tokenPublicKey = 'Gz3vYbpsB2agTsAwedtvtTkQ1CG9vsioqLW3r9ecNpvZ';

const run = async () => {
  try {
    const ownedMetadata = await programs.metadata.Metadata.load(connection, tokenPublicKey);
    console.log(ownedMetadata);
  } catch(error) {
    console.log('Failed to fetch metadata');
    console.log(error);
  }
};

function App() {

  return (
    <div className="App">
      <p onClick={run}>would be cool if it worked</p>
    </div>
  );
}

export default App;

I get an error as though programs.metadata.Metadata doesn't exist - "Cannot read properties of undefined (reading 'Metadata')". I even took this out of React and did a plain node script to just run the example code, which fails in the same way.

Any idea on how I could fix this?

Upvotes: 0

Views: 1542

Answers (1)

Mark Sackerberg
Mark Sackerberg

Reputation: 838

For users that find this question via search: There is now a better solution than using @metaplex-foundation/mpl-token-metadata directly. Have a look at @metaplex/js-next findByMint

Those lines should be all you need. imageUrl would be the image path.

import { Metaplex } from "@metaplex-foundation/js-next";
import { Connection, clusterApiUrl } from "@solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const metaplex = new Metaplex(connection);
const mint = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL");
const nft = await metaplex.nfts().findByMint(mint);
const imageUrl = nft.metadata.image;

Upvotes: 3

Related Questions