Skip to main content

useNFTContent

Fetches content for rendering from content URL in the NFT metadata#

This hook makes a request to fetch content (image, video, etc) based on an NFT's metadata.

Most metadata servers allow 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.

note

The same information can be fetched using the base MediaFetchAgent for server-side or non-React use.


Interface#

To use the hook, simply pass in the contentURI from the NFT's metadata and mimeType (image, video, audio etc). You can learn more about MIME types here.

If you do not have access to mimeType from the metadata or do not wish to retrieve the metadata, it can be omitted with a small performance impact.

Content returned from this hook is NOT CACHED, meaning that each time the hook is used the content will be fetched.

/** * @param uri URI of content to load or return URI for * @param mimeType MIME type expected for content * @returns useNFTContentType */
function useNFTContent(  uri?: string,  mimeType?: string,)

Response#

type useNFTContentType = {  error?: string;  content?: MediaContentType;}
type MediaContentType =  | { uri: string; type: 'uri'; mimeType: string }  | { text: string; type: 'text'; mimeType: string };

Code Example#

import { useNFTContent } from '@zoralabs/nft-hooks'
const MyMediaData = ({ uri: string, mimeType: string }) => {  const { error, content } = useNFTContent(uri, mimeType)
  if (error) {    return <div>Error fetching content</div>  }
  if (loading) {    return <div>loading...</div>  }
  if (content.type === 'text') {    return <div>{content.text}</div>  }  if (content.mimeType.startsWith('audio')) {    return <audio src={content.uri} />  }  if (content.mimeType.startsWith('video')) {    return <video src={content.uri} />  }  if (content.mimeType.startsWith('image')) {    return <img src={content.uri} />  }  return <div>unknown: {content.mimeType}</div>}

MediaFetchAgent#

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'
const fetchAgent = new MediaFetchAgent(Networks.MAINNET)
// Get result from the serverconst result = await fetchAgent.fetchContent(  'https://ipfs.io/ipfs/METADATA_HASH',  'application/json')// result type is MediaContentType