0

I was going through the following tutorial to implement a simple web3 app: https://learn.figment.io/tutorials/chakra-ui-with-solana-dapps#realtime-account-updates-using-polling-and-custom-react-hooks

This sets up an interval to monitor the status of an account so that it can display up to date information.

The function where the interval is set up is as follows:

function useSolanaAccount() {
const [account, setAccount] = useState(null);
const { connection } = useConnection();
const wallet = useWallet();

const init = useCallback(async () => {

    if(wallet.publicKey)
        console.log("usecallback publicKey:", wallet.publicKey.toString());
    else
        console.log("usecallback publicKey: None");
        
    if (wallet.publicKey) {
        let acc = await connection.getAccountInfo(wallet.publicKey);
        setAccount(acc);
    }

}, [wallet, connection]);

useEffect(() => {
    if (wallet.publicKey) {
        setInterval(init, 1000);
        console.log("use effect publicKey:", wallet.publicKey.toString());
    }
    else{
        console.log("clear interval");
        clearInterval(init);
    }
}, [init, wallet]);

return { account };
}

I've been trying to understand how to cancel the interval, and I really don't get it. From the console log it clearly reaches the code "clearInterval(init)", but it doesn't actually seem to do anything.

I've tried making init a global thing, which I read in another Stack Overflow post as a possible solution, but that didn't help.

TylerH
  • 20,799
  • 66
  • 75
  • 101
LindleyLentati
  • 161
  • 3
  • 12
  • 2
    you need to preserve `interval id`, and then use it in clearInterval call, from https://developer.mozilla.org/en-US/docs/Web/API/setInterval `check This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().` – Iłya Bursov Jun 26 '22 at 14:23
  • I see, i had thought i passed the function to the clearInterval, doing that and then setting it to null when clearing, and having the check if its not null when setting seems to work! thanky ou – LindleyLentati Jun 26 '22 at 14:41
  • you can call the same function with different intervals, this is why you need id – Iłya Bursov Jun 26 '22 at 16:58

0 Answers0