Skip to content

Commit 6871e73

Browse files
authored
Drop init argument when not needed in query key (#2061)
* Drop init argument when not needed in query key For urls that do not include an init param, generate a query key of length 2. This allows the value to be passed directly to `invalidateQueries()`. Without this change, the package generates `["get", "/foo", undefined]` which does not correctly match the corresponding get query. Related to #1806 * Create sour-steaks-double.md
1 parent 0a01774 commit 6871e73

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

.changeset/sour-steaks-double.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-react-query": patch
3+
---
4+
5+
Drop init argument when not needed in query key

packages/openapi-react-query/src/index.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ export type QueryKey<
3434
Paths extends Record<string, Record<HttpMethod, {}>>,
3535
Method extends HttpMethod,
3636
Path extends PathsWithMethod<Paths, Method>,
37-
> = readonly [Method, Path, MaybeOptionalInit<Paths[Path], Method>];
37+
Init = MaybeOptionalInit<Paths[Path], Method>,
38+
> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];
3839

3940
export type QueryOptionsFunction<Paths extends Record<string, Record<HttpMethod, {}>>, Media extends MediaType> = <
4041
Method extends HttpMethod,
@@ -199,7 +200,11 @@ export default function createClient<Paths extends {}, Media extends MediaType =
199200
};
200201

201202
const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => ({
202-
queryKey: [method, path, init as InitWithUnknowns<typeof init>] as const,
203+
queryKey: (init === undefined ? ([method, path] as const) : ([method, path, init] as const)) as QueryKey<
204+
Paths,
205+
typeof method,
206+
typeof path
207+
>,
203208
queryFn,
204209
...options,
205210
});

packages/openapi-react-query/test/index.test.tsx

+10
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,16 @@ describe("client", () => {
231231
expectTypeOf(result.current.data).toEqualTypeOf<"select(true)">();
232232
expectTypeOf(result.current.error).toEqualTypeOf<false | null>();
233233
});
234+
235+
it("returns query options without an init", async () => {
236+
const fetchClient = createFetchClient<minimalGetPaths>({
237+
baseUrl,
238+
fetch: () => Promise.resolve(Response.json(true)),
239+
});
240+
const client = createClient(fetchClient);
241+
242+
expect(client.queryOptions("get", "/foo").queryKey.length).toBe(2);
243+
});
234244
});
235245

236246
describe("useQuery", () => {

0 commit comments

Comments
 (0)