diff --git a/hooks/useLoadData/useLoadData.ts b/hooks/useLoadData/useLoadData.ts index b6c6e85..bd31b50 100644 --- a/hooks/useLoadData/useLoadData.ts +++ b/hooks/useLoadData/useLoadData.ts @@ -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'; @@ -30,6 +30,17 @@ function unboxApiResponse(arg: ApiResponse | 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(promisable: Promisable): promisable is Promise { + return ( + promisable instanceof Promise || + (promisable && typeof promisable === 'object' && 'then' in promisable && typeof promisable.then === 'function') + ); +} + export interface LoadDataConfig { fetchWhenDepsChange?: boolean; maxRetryCount?: number; @@ -186,7 +197,8 @@ export function useLoadData( } }, [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: