'How to check if user has a specific token by querying NFTBalances?
I am trying to check if a user has a specific token, in my case token_id should be "87". How can I check that using NFTBalances?
I wrote the code below but it is not working.
import React, { useState , useEffect } from "react";
import { useMoralis, useNFTBalances } from "react-moralis";
function Club() {
const { isInitialized } = useMoralis();
const { data: NFTBalances } = useNFTBalances()
const [isMember, setIsMember] = useState(false);
console.log(NFTBalances);
useEffect(() => {
async function fetchData() {
if (isInitialized) {
const NFTs = NFTBalances.result;
if (NFTBalances?.result) {
for (let NFT of NFTs) {
if(NFT.token_id=="87") {
setIsMember(true);
}
else {
setIsMember(false);
}
}
}
}
fetchData();
}}, [isInitialized]);
return (
<div>
{isMember? <div className="notification is-success">Welcome! You are a premium member of our club!</div>:<div>You don't have access to this page.</div>}
</div>
)
}
export default Club;
How can I fix it? It only shows that I don't have the token but I actually do. Am I doing anything wrong in the code? Is this the correct way to query the contents of NFTBalances?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|