Skip to content

fix: correctly check for promise in useLoadData #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 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,14 @@ 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 && typeof promisable === 'object' && 'then' in promisable && typeof promisable.then === 'function';
}

export interface LoadDataConfig {
fetchWhenDepsChange?: boolean;
maxRetryCount?: number;
Expand Down Expand Up @@ -186,7 +194,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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@optum/react-hooks",
"version": "1.0.4",
"version": "1.0.5-next.1",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should start looking at automating this

"description": "A reusable set of React hooks",
"repository": "https://github.com/Optum/react-hooks",
"license": "Apache 2.0",
Expand Down
Loading