From f33d9dad4782c81df9056e81da0e1a4174ae3298 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Wed, 6 Apr 2022 13:19:34 +0200 Subject: anastasis: use new truth API --- packages/anastasis-webui/src/hooks/async.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'packages/anastasis-webui/src') diff --git a/packages/anastasis-webui/src/hooks/async.ts b/packages/anastasis-webui/src/hooks/async.ts index 0fc197554..5235e1e3e 100644 --- a/packages/anastasis-webui/src/hooks/async.ts +++ b/packages/anastasis-webui/src/hooks/async.ts @@ -18,7 +18,7 @@ * * @author Sebastian Javier Marchano (sebasjm) */ -import { useState } from "preact/hooks"; +import { useCallback, useEffect, useRef, useState } from "preact/hooks"; // import { cancelPendingRequest } from "./backend"; export interface Options { @@ -34,6 +34,17 @@ export interface AsyncOperationApi { error: string | undefined; } +export function useIsMounted() { + const isMountedRef = useRef(true); + const isMounted = useCallback(() => isMountedRef.current, []); + + useEffect(() => { + return () => void (isMountedRef.current = false); + }, []); + + return isMounted; +} + export function useAsync( fn?: (...args: any) => Promise, { slowTolerance: tooLong }: Options = { slowTolerance: 1000 }, @@ -42,11 +53,15 @@ export function useAsync( const [isLoading, setLoading] = useState(false); const [error, setError] = useState(undefined); const [isSlow, setSlow] = useState(false); + const isMounted = useIsMounted(); const request = async (...args: any) => { if (!fn) return; setLoading(true); const handler = setTimeout(() => { + if (!isMounted()) { + return; + } setSlow(true); }, tooLong); @@ -54,6 +69,10 @@ export function useAsync( console.log("calling async", args); const result = await fn(...args); console.log("async back", result); + if (!isMounted()) { + // Possibly calling fn(...) resulted in the component being unmounted. + return; + } setData(result); } catch (error) { setError(error); -- cgit v1.2.3