From 462ba93f76a571b4a6d31170b4ed0ed9894072c7 Mon Sep 17 00:00:00 2001 From: Michael Peters Date: Sun, 21 Jul 2024 10:59:45 -0700 Subject: [PATCH] useOneTimeAsyncAction -> useAsyncMemo --- src/core/hooks.ts | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/core/hooks.ts b/src/core/hooks.ts index 63f2cf1..8a5630a 100644 --- a/src/core/hooks.ts +++ b/src/core/hooks.ts @@ -30,51 +30,55 @@ export function useIsMountedRef() { } /** returns a boolean state that will be true for a specified duration after the doShake function is called */ -function useShake(ms: number): [shaking: boolean, doShake: () => void] { +function usePulse(ms: number): [shaking: boolean, doPulse: () => void] { const isMounted = useIsMountedRef(); - const [shaking, setShaking] = useState(false); + const [pulsing, setPulsing] = useState(false); - const doShake = useCallback(async () => { + const doPulse = useCallback(async () => { if (!isMounted.current) return; - if (shaking) return; - setShaking(true); + if (pulsing) return; + setPulsing(true); await sleep(ms); if (!isMounted.current) return; - setShaking(false); - }, [isMounted, ms, shaking]); + setPulsing(false); + }, [isMounted, ms, pulsing]); - return [shaking, doShake]; + return [pulsing, doPulse]; } // runs an Async action one time (updates when deps changes) -export function useOneTimeAsyncAction( - actionFunc: () => Promise, +export function useAsyncMemo( + calculateValue: () => Promise, deps: DependencyList, initialValue: V, -): [value: T | V, error: unknown | null] { +): [value: T | V, pending: boolean, error: unknown | null] { const isMounted = useIsMountedRef(); const [value, setValue] = useState(initialValue); + const [pending, setPending] = useState(false); const [error, setError] = useState(null); useEffect(() => { + setPending(true); (async () => { try { - const value = await actionFunc(); + const value = await calculateValue(); if (!isMounted.current) return; setValue(value); + setPending(false); setError(null); } catch (e: unknown) { console.error('unable to perform async action subscription', e); if (!isMounted.current) return; + setPending(false); setError(e); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [actionFunc, ...deps]); + }, [calculateValue, ...deps]); - return [value, error]; + return [value, pending, error]; } /** creates a callable async function that will not double-trigger and gives a result, error message, and shaking boolean */ @@ -88,7 +92,7 @@ export function useAsyncCallback( const [result, setResult] = useState(null); const [errorMessage, setErrorMessage] = useState(null); - const [shaking, doShake] = useShake(400); + const [shaking, doShake] = usePulse(400); const [pending, setPending] = useState(false);