Skip to content

Commit

Permalink
Merge pull request #33 from lifeomic/support-select
Browse files Browse the repository at this point in the history
fix: correctly support select(...) option for useAPIQuery
  • Loading branch information
swain authored Aug 21, 2023
2 parents e57d856 + b21b057 commit 4e341e4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 9 deletions.
24 changes: 24 additions & 0 deletions src/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,30 @@ describe('useAPIQuery', () => {
);
});
});

test('using select(...) works and is typed correctly', async () => {
network.mock('GET /items', {
status: 200,
data: { message: 'test-message' },
});

const screen = render(() => {
const query = useAPIQuery(
'GET /items',
{ filter: 'test-filter' },
{ select: (data) => data.message },
);

// This line implicitly asserts that `query.data` is typed as string.
query.data?.codePointAt(0);

return <div data-testid="content">{query.data || ''}</div>;
});

await TestingLibrary.waitFor(() => {
expect(screen.queryByText('test-message')).toBeDefined();
});
});
});

describe('useInfiniteAPIQuery', () => {
Expand Down
30 changes: 21 additions & 9 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,20 @@ export type RequestPayloadOf<
Route extends keyof Endpoints,
> = Endpoints[Route]['Request'] & PathParamsOf<Route>;

type RestrictedUseQueryOptions<Response> = Omit<
UseQueryOptions<Response, unknown>,
'queryKey' | 'queryFn'
> & {
type RestrictedUseQueryOptions<
Response,
TError = unknown,
Data = Response,
> = Omit<UseQueryOptions<Response, TError, Data>, 'queryKey' | 'queryFn'> & {
axios?: AxiosRequestConfig;
};

type RestrictedUseInfiniteQueryOptions<Response, Request> = Omit<
UseInfiniteQueryOptions<Response, unknown>,
type RestrictedUseInfiniteQueryOptions<
Response,
Request,
Data = Response,
> = Omit<
UseInfiniteQueryOptions<Response, unknown, Data>,
'queryKey' | 'queryFn' | 'getNextPageParam' | 'getPreviousPageParam'
> & {
axios?: AxiosRequestConfig;
Expand Down Expand Up @@ -132,11 +137,18 @@ export type CacheUtils<Endpoints extends RoughEndpoints> = {
};

export type APIQueryHooks<Endpoints extends RoughEndpoints> = {
useAPIQuery: <Route extends keyof Endpoints & string>(
useAPIQuery: <
Route extends keyof Endpoints & string,
Data = Endpoints[Route]['Response'],
>(
route: Route,
payload: RequestPayloadOf<Endpoints, Route>,
options?: RestrictedUseQueryOptions<Endpoints[Route]['Response']>,
) => UseQueryResult<Endpoints[Route]['Response']>;
options?: RestrictedUseQueryOptions<
Endpoints[Route]['Response'],
unknown,
Data
>,
) => UseQueryResult<Data>;

useInfiniteAPIQuery: <Route extends keyof Endpoints & string>(
route: Route,
Expand Down

0 comments on commit 4e341e4

Please sign in to comment.