Skip to content

Commit

Permalink
Update usePromise.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandarDev authored Sep 15, 2023
1 parent 2606d82 commit 04263e3
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions packages/react-hooks/hooks/usePromise.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
useEffect,
useRef,
useState,
useTransition
} from 'react';
Expand Down Expand Up @@ -34,40 +33,37 @@ export type PromiseFunction<T> = (Promise<T> | undefined) | (() => Promise<T> |
export function usePromise<T>(promise?: PromiseFunction<T>): UsePromiseResult<T> {
const [state, setState] = useState<UsePromiseResult<T>>({ isLoading: true, item: undefined, error: undefined });
const [, startTransition] = useTransition();
const loadPromiseRef = useRef<Promise<T> | undefined>(undefined);

useEffect(() => {
let canceled = false;

// Ignore if promise not provided or already loading and not canceled
if (!promise || (loadPromiseRef.current && !canceled)) {
// Ignore if promise not provided
if (!promise) {
return;
}

setState((curr) => ({ ...curr, isLoading: true }));

// Resolve as promise object or function
loadPromiseRef.current = typeof promise === 'function' ? promise() : promise;
const current = typeof promise === 'function' ? promise() : promise;

// If promise is undefined, load is considered complete and empty
if (!loadPromiseRef.current) {
if (!current) {
startTransition(() => {
setState({ isLoading: false });
});
return;
}

loadPromiseRef.current
current
.then(item => {
loadPromiseRef.current = undefined;
if (canceled) {
return;
}
startTransition(() => {
setState({ isLoading: false, item });
});
}).catch(err => {
loadPromiseRef.current = undefined;
if (canceled) {
return;
}
Expand Down

0 comments on commit 04263e3

Please sign in to comment.