Search code examples
reactjsnearprotocol

Call contract method from React


I'm new to React and NEAR and trying to understand how my frontend React app can call methods on the contract.

In the near cli i can call near view $NFT_CONTRACT_ID nft_total_supply which returns the amount of NFTs on the contract.

How do i call the same method from React.

I'm trying

  export async function CheckSupply() {
    const near = await connect(getConfig);
    const account = await near.account("mytestnetaccount.testnet");
    const supply = window.contract.nft_total_supply();
    console.log("please print this out")
  }

In my App.js i have a very basic page for now just to test the console.log() is being written out

const App = () =>{
  window.Buffer = window.Buffer || require("buffer").Buffer;
    const [userHasNFT, setuserHasNFT] = useState(false);  
   
    return (
        <>
        <div className="app">
            <WalletLogin />
            
            <div className="container">
            
                <img
                    alt=""
                    src={Logo}
                    width="360"
                    height="150"
                    className="d-inline-block align-top"
                />

            </div>
</>
};


But when I launch the app nothing is being written to the console.

I'm not sure why, but thinking it's because the function CheckSupply is not being called, but I want this to run when the app is rendered.

The function CheckSupply() is within my utils.js and being imported using import { CheckSupply } from "./utils";

Thanks


Solution

  • If you want to call a function on mount in react functional component you can call that function in use effect with empty dependency array

    checkout the code below and the link to learn more about effects in react

    import { CheckSupply } from "./utils";
    import {useEffect} from 'react';
        
    const App = () =>{
    
    window.Buffer = window.Buffer || require("buffer").Buffer;
    
    const [userHasNFT, setuserHasNFT] = useState(false);  
    
    useEffect(()=>{
        CheckSupply();
    },[])
    
    return (
        <>
        <div className="app">
            <WalletLogin />
            
            <div className="container">
            
                <img
                    alt=""
                    src={Logo}
                    width="360"
                    height="150"
                    className="d-inline-block align-top"
                />
    
            </div>
        </>
    };
    

    https://reactjs.org/docs/hooks-effect.html