Displaying totalSupply on page and refreshing every x seconds ReactJS

Hey guys,

i have some trouble understanding how to use the web3 API …

i have the below code

const Web3Api = useMoralisWeb3Api()
const options = {
  chain: "0x38",
  address: "contractAddress",
  function_name: "totalSupply",
  abi: contract

const fetchTotalSupply = async() => {
  const totalSupply = await Web3Api.native.runContractFunction(options);
  return totalSupply;

I need to now display this totalSupply on the page in a

and refresh it every 5-10 seconds… how can i go about to do this, i am struggling i tried to call the function directly like this

<div>{ fetchTotalSupply }</div>

but it doesn’t work, what could i be doing wrong?

1 Like

Hi @Koolguy69

You don’t need to put your functions to the JSX component code like this:
<div>{ fetchTotalSupply }</div>

If you want to call your function with interval you need to use setInterval and useEffect hook.

Instead of using whole useMoralisWeb3Api you can use useWeb3ExecuteFunction() = Web3Api.native.runContractFunction()


const YourComponent = () => {
    const options = {
        chain: "0x38",
        address: "contractAddress",
        function_name: "totalSupply",
        abi: contract

    const { data, error, fetch, isFetching, isLoading } =

    useEffect(() => {      
        const interval = setInterval(() => {
            console.log('This will run every second!');
        }, 1000);
        return () => clearInterval(interval);
    }, []);

    return (
        {error && <ErrorMessage error={error} />}
        <button onClick={() => fetch()} disabled={isFetching}>Fetch data</button>
        {data && <pre>

You don’t need to write your code like this:
const totalSupply = await Web3Api.native.runContractFunction(options)
because after each new fetching the data object returned from the hook will be updated so you can simply put it to your code as fresh info

Hope this helps

1 Like

thank you very much for your help sir!
much appreciated! let me work on this