Skip to content

Commit

Permalink
fix: correctly check for promise in useLoadData
Browse files Browse the repository at this point in the history
  • Loading branch information
NielsJPeschel committed Jan 9, 2025
1 parent aeb827c commit c69bc39
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions hooks/useLoadData/useLoadData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useEffect, useState, useMemo} from 'react';
import {ApiResponse, RetryResponse, ApiResponseBase, OptionalDependency, DependencyBase} from '../../types';
import {ApiResponse, RetryResponse, ApiResponseBase, OptionalDependency, DependencyBase, Promisable} from '../../types';

import {FetchData, NotUndefined} from './types';

Expand Down Expand Up @@ -30,6 +30,17 @@ function unboxApiResponse<T>(arg: ApiResponse<T> | T): T {
}
}

/*
isPromise determines a promise by checking whether or not it is an instanceof
native promise (preferred) or whether it has a then method.
*/
function isPromise<T>(promisable: Promisable<T>): promisable is Promise<T> {
return (
promisable instanceof Promise ||
(promisable && typeof promisable === 'object' && 'then' in promisable && typeof promisable.then === 'function')
);
}

export interface LoadDataConfig {
fetchWhenDepsChange?: boolean;
maxRetryCount?: number;
Expand Down Expand Up @@ -186,7 +197,8 @@ export function useLoadData<T extends NotUndefined, Deps extends any[]>(
}
}, [counter, localFetchWhenDepsChange]);

const nonPromiseResult = initialPromise.res instanceof Promise ? undefined : initialPromise.res;
const initialPromiseRes = initialPromise.res;
const nonPromiseResult = isPromise(initialPromiseRes) ? undefined : initialPromiseRes;
const initialData = data || nonPromiseResult;

// Initialize our pending data to one of three possible states:
Expand Down

0 comments on commit c69bc39

Please sign in to comment.