From 7e5681b99411ae2a00967b2aeaaf10278df1ede4 Mon Sep 17 00:00:00 2001 From: Ryo Komiyama Date: Tue, 23 Jul 2024 17:14:24 +0900 Subject: [PATCH] Add cleanup function to useEffect --- .../src/hooks/useCounterContract.step7.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/03-client/test/src/hooks/useCounterContract.step7.ts b/03-client/test/src/hooks/useCounterContract.step7.ts index 35342a6..146a16b 100644 --- a/03-client/test/src/hooks/useCounterContract.step7.ts +++ b/03-client/test/src/hooks/useCounterContract.step7.ts @@ -11,7 +11,7 @@ export function useCounterContract() { const { sender } = useTonConnect(); const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time)); - + const counterContract = useAsyncInitialize(async () => { if (!client) return; const contract = new Counter( @@ -21,15 +21,24 @@ export function useCounterContract() { }, [client]); useEffect(() => { + let isCancelled = false; + async function getValue() { - if (!counterContract) return; + if (!counterContract || isCancelled) return; setVal(null); const val = await counterContract.getCounter(); - setVal(val.toString()); - await sleep(5000); // sleep 5 seconds and poll value again - getValue(); + if (!isCancelled) { + setVal(val.toString()); + await sleep(5000); // sleep 5 seconds and poll value again + getValue(); + } } + getValue(); + + return () => { + isCancelled = true; + }; }, [counterContract]); return {