Skip to content

Commit d550533

Browse files
authored
Merge pull request #1 from 7nohe/feature/export-query-keys
feat: export query keys
2 parents 0f4d602 + c1418cf commit d550533

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
## Features
66

77
- Supports generation of custom react hooks that use React Query's `useQuery` and `useMutation` hooks
8+
- Supports generation of query keys for query caching
89
- Supports the option to use pure TypeScript clients generated by [OpenAPI Typescript Codegen](https://github.com/ferdikoomen/openapi-typescript-codegen)
910

1011
## Install
@@ -81,8 +82,13 @@ You can also use pure TS clients.
8182
```tsx
8283
import { useQuery } from "@tanstack/react-query";
8384
import { PetService } from '../openapi/requests/services/PetService';
85+
import {
86+
usePetServiceFindPetsByStatusKey,
87+
} from "../openapi/queries";
88+
8489
function App() {
85-
const { data } = useQuery(['MyKey'], () => {
90+
// You can still use the auto-generated query key
91+
const { data } = useQuery([usePetServiceFindPetsByStatusKey], () => {
8692
// Do something here
8793

8894
return PetService.findPetsByStatus(['available']);

src/createUseQuery.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,30 @@ export const createUseQuery = (
3939
),
4040
);
4141
}
42-
return ts.factory.createVariableStatement(
42+
43+
const customHookName = `use${className}${capitalizeFirstLetter(methodName)}`;
44+
const queryKey = `${customHookName}Key`
45+
46+
return [
47+
ts.factory.createVariableStatement(
48+
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
49+
ts.factory.createVariableDeclarationList(
50+
[ts.factory.createVariableDeclaration(
51+
ts.factory.createIdentifier(queryKey),
52+
undefined,
53+
undefined,
54+
ts.factory.createStringLiteral(`${className}${capitalizeFirstLetter(methodName)}`)
55+
)],
56+
ts.NodeFlags.Const
57+
)
58+
),
59+
ts.factory.createVariableStatement(
4360
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
4461
ts.factory.createVariableDeclarationList(
4562
[
4663
ts.factory.createVariableDeclaration(
4764
ts.factory.createIdentifier(
48-
`use${className}${capitalizeFirstLetter(methodName)}`
65+
customHookName
4966
),
5067
undefined,
5168
undefined,
@@ -146,9 +163,7 @@ export const createUseQuery = (
146163
[
147164
ts.factory.createArrayLiteralExpression(
148165
[
149-
ts.factory.createStringLiteral(
150-
`${className}${capitalizeFirstLetter(methodName)}`
151-
),
166+
ts.factory.createIdentifier(queryKey),
152167
ts.factory.createSpreadElement(ts.factory.createIdentifier("queryKey"))
153168
],
154169
false
@@ -178,5 +193,5 @@ export const createUseQuery = (
178193
],
179194
ts.NodeFlags.Const
180195
)
181-
);
196+
)];
182197
};

0 commit comments

Comments
 (0)