Skip to main content

useNFTMetadata

Fetches NFT metadata from a URL#

This hook makes a request to fetch metadata from a NFT's metadataURI.

Most metadata servers allow for remote JSON fetches, however, there is a chance this request could fail. Requests are set with a 10 second timeout to allow showing the user an error message instead of an indefinite loader.

Metadata information can be found in the ZORA metadata schema repo. Metadata validation can be ignored optionally by passing in a second argument {allowInvalid: true} to the hook. By default, an error will be thrown for invalid metadata and the metadata result will be undefined.

Hook Result Type#
type useNFTMetadataType = {  error?: string // Error: can be thrown from invalid json, unparsable json, network request failure, network request timeout  loading?: boolean // Easy indicator to determine if the NFT metadata is loading. Same as (!metadata && !error).  metadata?: any // Raw, validated ZORA metadata. A error will be thrown if the metadata does not validate.}

Pass in the metadata URL to fetch the NFT data:

import { useNFTMetadata } from '@zoralabs/nft-hooks'
const MediaDataDisplay = ({ uri: string }) => {  const { error, metadata } = useNFTMetadata(uri)
  if (metadata) {    return (      <div>        <h2>Name: {metadata.name}</h2>        <p>{metadata.description}</p>      </div>    )  }
  if (error) {    return <div>Error loading metadata</div>  }  return <div>metadata loading...</div>}

Alternatively, the same information can be fetched using the base MediaFetchAgent for server-side or non-React use:

import { MediaFetchAgent, Networks } from '@zoralabs/nft-hooks'
// Be careful making multiple instances of the fetch agent// Each instance contains a different request cache.const fetchAgent = new MediaFetchAgent(Networks.MAINNET)
// Get result from the serverconst result = await fetchAgent.loadMetadata('https://ipfs.io/ipfs/METADATA_HASH')// result type is {metadata, valid}