id | title | sidebar_position |
---|---|---|
usenftmetadata |
useNFTMetadata |
3 |
This hook makes a request to fetch metadata from an 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.
:::note
The same information can be fetched using the base MediaFetchAgent
for server-side or non-React use.
:::
Pass in the metadata URL to fetch the NFT data:
/**
* @param uri URI of metadata to fetch
* @returns @type useNFTMetadataType
*/
export function useNFTMetadata(
uri?: string,
)
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 metadata based on the URI passed in
}
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 results from the server
const result = await fetchAgent.fetchIPFSMetadata('https://ipfs.io/ipfs/METADATA_HASH')
// result type is {metadata}