From a7ccbcfca4f181790b86199a7f31d1ae19e0253f Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 31 Aug 2022 20:47:07 +0200 Subject: Refactor webpack; Add ErrorBoundary --- src/utils/misc.tsx | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) (limited to 'src/utils') diff --git a/src/utils/misc.tsx b/src/utils/misc.tsx index ded052b..aca7661 100644 --- a/src/utils/misc.tsx +++ b/src/utils/misc.tsx @@ -1,4 +1,4 @@ -import { React } from "../webpack"; +import { React } from "../webpack/common"; /** * Makes a lazy function. On first call, the value is computed. @@ -16,17 +16,28 @@ export function lazy(factory: () => T): () => T { * Await a promise * @param factory Factory * @param fallbackValue The fallback value that will be used until the promise resolved - * @returns A state that will either be null or the result of the promise + * @returns [value, error, isPending] */ -export function useAwaiter(factory: () => Promise, fallbackValue: T | null = null): T | null { - const [res, setRes] = React.useState(fallbackValue); +export function useAwaiter(factory: () => Promise): [T | null, any, boolean]; +export function useAwaiter(factory: () => Promise, fallbackValue: T): [T, any, boolean]; +export function useAwaiter(factory: () => Promise, fallbackValue: T | null = null): [T | null, any, boolean] { + const [state, setState] = React.useState({ + value: fallbackValue, + error: null as any, + pending: true + }); React.useEffect(() => { - factory().then(setRes); + let isAlive = true; + factory() + .then(value => isAlive && setState({ value, error: null, pending: false })) + .catch(error => isAlive && setState({ value: null, error, pending: false })); + + return () => void (isAlive = false); }, []); - return res; -} + return [state.value, state.error, state.pending]; +}; /** * A lazy component. The factory method is called on first render. For example useful -- cgit