Functions are not updating after refresh

Is it possible for you to add a button to refresh the lottery status?

If you want it run through different react renders, you need to make sure you need it only depending on the react variables.

This is an example contract from one of my projects where the contract function runs automatically whenever there is a change in metadataHash variable. And I did not use enableWeb3 here because the entire dom loads only when isWeb3Enabled, so web3 is always enabled for the contract functions to run.
You can implement something like this in your code to run the smart contract function on its own.

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction({
    abi: ABI,
    contractAddress: contractAddress,
    functionName: "safeMint",
    params: {
      uri: metadataHash,
    },
  });

  useEffect(() => {
    if (
      metadataHash !== "" &&
      metadataHash !== null &&
      prevMetadataHash.current !== metadataHash) {
      prevMetadataHash.current = metadataHash;
      fetch();
    }
  }, [metadataHash]);

And is there any require function in your isOpen contract function, to allow only owner to call the function?
When I try to call the smart contact function it throws me an error from smart contract, so I did not modify that part of code.

I am not getting the point that you are trying to explian me, can you share any video tutorial of moralis that shows the same you are trying to tell me.

I don’t have any tutorial related to this.

I wrote a simple code on what I was trying to explain.
This code reads data from the smart contract function after the user login and displays it on the app.

Try importing this to your app and test it.

import React, { useEffect } from "react";
import { useMoralis } from "react-moralis";
import { useChain, useWeb3ExecuteFunction } from "react-moralis";
import { useState } from "react";

function Test() {
  const {
    authenticate,
    isAuthenticated,
    isAuthenticating,
    user,
    logout,
    web3,
    enableWeb3,
    isWeb3Enabled,
    Moralis,
  } = useMoralis();
  const { switchNetwork, chainId, chain, account } = useChain();
  const [contractAddress, setContractAddress] = useState(
    "0x36d53FB0c43a124a7b0f4a23E80C1a3980E67dCB"
  );
  const [abi, setAbi] = useState([
    {
      inputs: [],
      name: "data",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        },
      ],
      stateMutability: "view",
      type: "function",
    },
  ]);
  function changeChain() {
    switchNetwork("0x13881");
  }
  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction({
    abi: abi,
    contractAddress: contractAddress,
    functionName: "data",
  });

  useEffect(() => {
    if (isWeb3Enabled) {
      fetch();
    }
  }, [isWeb3Enabled]);

  useEffect(() => {
    if (data) {
      console.log(data);
    }
  }, [data]);
  useEffect(() => {
    if (error) {
      console.log(error);
    }
  }, [error]);
  useEffect(() => {
    if (web3) {
      console.log(web3._isProvider);
    }
  }, [web3]);

  if (!isAuthenticated) {
    return (
      <div>
        <button onClick={() => authenticate()}>Login</button>
      </div>
    );
  }

  if (isAuthenticated && chainId !== "0x13881") {
    if (!isWeb3Enabled) {
      enableWeb3();
    }
    return <button onClick={changeChain}>Switch Network</button>;
  } else if (isWeb3Enabled && chainId === "0x13881") {
    return (
      <div>
        <div>The data from contract: {data}</div>
        <button onClick={logout}>logout</button>
      </div>
    );
  }
}
export default Test;

Hope this helps.

Here’s a little fix to your app.js to handle that.

import {
  useMoralis,
  useMoralisWeb3Api,
  useMoralisWeb3ApiCall,
} from "react-moralis";
import swal from "sweetalert";
import React, { useEffect } from "react";
import abi from "./abi.json";

function App() {
  const [par, setPar] = React.useState(0);
  const [bal, setBal] = React.useState(0);
  const [min, setMin] = React.useState(0);
  const [status, setStatus] = React.useState(false);
  const {
    authenticate,
    isAuthenticated,
    user,
    account,
    logout,
    isWeb3Enabled,
    enableWeb3,
    isInitialized,
  } = useMoralis();
  const { Moralis } = useMoralis();
  const { native } = useMoralisWeb3Api();
  const { fetch } = useMoralisWeb3ApiCall(native.runContractFunction);

  useEffect(() => {
    if (!isWeb3Enabled && isAuthenticated) enableWeb3();
  }, [isWeb3Enabled, isAuthenticated]);

  async function login() {
    if (!isAuthenticated) {
      await authenticate();
    }
  }

  async function exit() {
    await logout();
  }

  useEffect(() => {
    if (isInitialized && isAuthenticated) {
      lotteryStatus();
      minContribution();
    }
  }, [isAuthenticated, isInitialized]);

  async function enterLottery() {
    // Write Function
    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
      functionName: "enterLottery",
      abi,
      msgValue: await Moralis.Units.ETH(prompt("Enter the amount in ETH:")),
    };

    const transaction = await Moralis.executeFunction(sendOptions);
  }

  async function minContribution() {
    //Read Function
    let result = await fetch({
      params: {
        chain: "ropsten",
        address: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
        function_name: "getminContribution",
        abi,
      },
    });
    console.log("RESULT FROM " + result);
    setMin(Moralis.Units.FromWei(result));
  }

  async function pickWinner() {
    //Write Function
    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
      functionName: "pickWinner",
      abi,
    };
    const transaction = await Moralis.executeFunction(sendOptions);
    setStatus(false);
  }

  async function getBalance() {
    // Read Function

    let result = await fetch({
      params: {
        chain: "ropsten",
        address: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
        function_name: "getBalance",
        abi,
      },
    });
    console.log("BALANCE FROM " + result);
    setBal(Moralis.Units.FromWei(result));
  }

  async function getParticipants() {
    // Read Function
    let result = await fetch({
      params: {
        chain: "ropsten",
        address: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
        function_name: "getParticipants",
        abi,
      },
    });
    console.log("PARTICIPANTS FROM " + result);

    swal({
      title: `Participants: ${Moralis.Units.FromWei(result, 0)}`,
      icon: "info",
    });
  }

  async function startLottery() {
    // Write Function
    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
      functionName: "startLottery",
      abi,
    };
    const transaction = await Moralis.executeFunction(sendOptions);
    setStatus(true);
  }

  async function lotteryStatus() {
    // Read Function
    let result = await fetch({
      params: {
        chain: "ropsten",
        address: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
        function_name: "isOpen",
        abi,
      },
    });
    console.log("LOTTERY STATUS " + result);

    setStatus(result);
  }

  return (
    <>
      <div className="card text-center bg2">
        <div className="card-body bg2">
          {/* {isAuthenticated? <button type="button" className="btn btn-outline-warning" onClick={Update}>Balance: {balances}</button> : null} */}
          {isAuthenticated ? (
            <p className="lottery">Lottery : {status ? "Running" : "Closed"}</p>
          ) : (
            <p className="lottery">Lottery</p>
          )}
          {isAuthenticated ? (
            <p className=" text-gradient">Account : {user.get("ethAddress")}</p>
          ) : (
            <p className=" text-gradient">Account : Not Connected</p>
          )}
          {isAuthenticated ? <p className=" text-gradient">{null}</p> : null}
          {isAuthenticated ? (
            <p className="min">Minimum Contribution : {min} ETH</p>
          ) : null}
          {isAuthenticated ? (
            <button className="button-custom" onClick={getParticipants}>
              INFO
            </button>
          ) : null}
          &nbsp; &nbsp;
          {!isAuthenticated ? (
            <button
              type="button"
              className="btn btn-outline-light button-85"
              onClick={login}
            >
              Connect to metamask
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated ? (
            <button type="button" className="button-33" onClick={enterLottery}>
              Enter Lottery
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated &&
          user.get("ethAddress") ===
            "0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase() ? (
            <button
              type="button"
              className="btn btn-outline-success"
              onClick={startLottery}
            >
              Start Lottery
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated &&
          user.get("ethAddress") ===
            "0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase() ? (
            <button
              type="button"
              className="btn btn-outline-primary"
              onClick={pickWinner}
            >
              Pick Winner
            </button>
          ) : null}
          &nbsp; &nbsp;
          {isAuthenticated ? (
            <button type="button" className="button-78" onClick={exit}>
              Logout
            </button>
          ) : null}
        </div>
        <div className="card-footer text-gradient">Copyright @Abir Dutta</div>
      </div>
    </>
  );
}

export default App;

Hey mate it’s working fine completely thank you for you help and support.