From 0c4de5d56a3ae89196fc27893470822cc60f9d42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20T=C3=B6lle?= Date: Sat, 25 Jun 2022 17:41:14 +0200 Subject: [PATCH] feat(frontend): use transition for showing new data --- frontend/src/hooks/use-async.tsx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/frontend/src/hooks/use-async.tsx b/frontend/src/hooks/use-async.tsx index 004f8c5..3f5e819 100644 --- a/frontend/src/hooks/use-async.tsx +++ b/frontend/src/hooks/use-async.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useState, useTransition } from "react"; type UseAsync = ( asyncFunction: () => Promise, @@ -17,19 +17,23 @@ export const useAsync: UseAsync = ( const [pending, setPending] = useState(false); const [value, setValue] = useState(initialValue); const [error, setError] = useState(null); + const [, startTransition] = useTransition(); // The execute function wraps asyncFunction and // handles setting state for pending, value, and error. // useCallback ensures the below useEffect is not called // on every render, but only if asyncFunction changes. const execute = useCallback(() => { - setPending(true); - setValue(initialValue); - setError(null); + startTransition(() => { + setPending(true); + setValue(initialValue); + setError(null); + }); + return asyncFunction() - .then((response) => setValue(response)) - .catch((err) => setError(err)) - .finally(() => setPending(false)); + .then((response) => startTransition(() => setValue(response))) + .catch((err) => startTransition(() => setError(err))) + .finally(() => startTransition(() => setPending(false))); }, [asyncFunction, initialValue]); // Call execute if we want to fire it right away.