I was mistaken, the token ID wasn’t in the metadata. It’s only in the results returned by the query.
I did a check to see if the search term is a number and used getTokenIdMetadata
if it is.
I also use a debounce on the search bar to wait for the user to finish input so it’s not calling the API for every character.
function containsTokenId(str: string): boolean {
const regex =
/^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9][0-9])$/;
return regex.test(str);
}
const searchNFT = async () => {
try {
if (search === '') {
return;
}
const isTokenId = containsTokenId(search);
// Moralis: getTokenIdMetadata
if (isTokenId) {
const queryOptions: {
token_address: string;
chain: string;
} = {
token_address: `${process.env.NEXT_PUBLIC_ADRESSS}`,
chain: `${process.env.NEXT_PUBLIC_CHAIN}`,
};
const options = {
method: 'GET',
headers: {
accept: 'application/json',
'X-API-Key': web3ApiKey,
},
};
const url = new URL(
`https://deep-index.moralis.io/api/v2/nft/${queryOptions.token_address}/${search}?chain=${queryOptions.chain}&format=decimal`
);
const res = await fetch(url, options);
if (!res.ok) {
const message = `An error has occured: ${res.status}`;
throw new Error(message);
}
const response = await res.json();
const nft = response;
const arr = [];
arr.push(nft);
return arr;
}
// Moralis: searchNFTs
const queryOptions: {
token_address: string;
chain: string;
} = {
token_address: `${process.env.NEXT_PUBLIC_ADRESSS}`,
chain: `${process.env.NEXT_PUBLIC_CHAIN}`,
};
const options = {
method: 'GET',
headers: {
accept: 'application/json',
'X-API-Key': web3ApiKey,
},
};
const url = new URL(
`https://deep-index.moralis.io/api/v2/nft/search?chain=${queryOptions.chain}&format=decimal&q=${search}&filter=name&addresses=${queryOptions.token_address}&token_address=${queryOptions.token_address}`
);
const res = await fetch(url, options);
if (!res.ok) {
const message = `An error has occured: ${res.status}`;
throw new Error(message);
}
const response = await res.json();
const nfts = response.result;
return nfts;
} catch (err) {
console.error(err);
}
};