react-query-hook-builder
v0.0.7
Published
A simple extension to help you create hooks that can be used inside your codebase
Downloads
12
Maintainers
Readme
React Query Hook Builder
A powerful tool to streamline your React Query development workflow. It automates the generation of type-safe hooks, API functions, query keys, and TypeScript types directly from OpenAPI specifications or manual inputs.
Available as both a VS Code Extension and an npm package for programmatic use.
Installation
VS Code Extension
Install from the VS Code Marketplace
npm Package
npm install react-query-hook-builder
# or
yarn add react-query-hook-builderFeatures
🚀 OpenAPI / Swagger Support
- Import from URL or JSON: Easily load your API specification by providing a URL or pasting the JSON content directly.
- Batch Generation: Select multiple API endpoints at once to generate hooks in bulk.
- Smart Detection:
- Automatically maps
GETrequests touseQuery. - Maps
POST,PUT,DELETEtouseMutation. - Pagination Support: Detects paginated responses (e.g., fields like
totalRecords) and generatesuseInfiniteQuerywith mostly completegetNextPageParamlogic.
- Automatically maps
- Type Generation: Generates comprehensive TypeScript interfaces for:
- Request Variables: Parameters (path/query) and request bodies.
- Response Models: Strongly typed response objects, handling deeply nested structures and extracting cleaner names (e.g.,
UserDatavs genericResponse).
🛠️ Manual Hook Generation
- Generate Hook from Specs: Don't have an OpenAPI spec? No problem.
- Interactively provide the Feature Name, API URL, and HTTP Method.
- Paste an example JSON response to automatically infer and generate TypeScript interfaces.
📦 Modular Code Generation
The extension generates four distinct parts for each hook, which can be placed in separate files or combined as needed:
- Models/Types: TypeScript interfaces for the API response and variables.
- API Function: An
axios-based async function to make the network request. - Query Keys: A standardized factory object for React Query keys (supporting easy invalidation and scoping).
- Hook: The custom React hook (
useUser,useCreateUser, etc.) wrapping the React Query logic.
⚡ Developer Experience
- Append to Files: Seamlessly append generated code to existing standard files (e.g., adding a new type to
types.tsor a new hook touseHooks.ts). - History Support: Remembers your recently used OpenAPI URLs for quick access.
- Formatting: Automatically formats generated code using a built-in Prettier implementation to match standard style guides.
Usage
VS Code Extension
Method 1: Generate from OpenAPI (Recommended)
- Open the Command Palette (
Cmd+Shift+PorCtrl+Shift+P). - Run "React Query Hook Builder: Generate Hook from OpenAPI Spec".
- Source: Select "Enter new OpenAPI Spec URL or JSON content" (or pick from history).
- Select Endpoints: Choose one or more operations from the list.
- Destination: For each component (Models, API, Keys, Hooks), choose to:
- Select an existing file to append to.
- Create a new file.
- (The extension will remember your last used file for faster re-runs).
Method 2: Generate from Manual Specs
- Open the Command Palette.
- Run "React Query Hook Builder: Generate Hook from specs".
- Follow the prompts:
- Feature Name: e.g.,
TodoList. - Method:
GET,POST, etc. - API URL: e.g.,
/api/todos. - Example Response: Paste a JSON sample from your backend to generate types.
- Feature Name: e.g.,
npm Package (Programmatic Usage)
import { generateFiles, parseOpenApiSpec, formatCode } from 'react-query-hook-builder';
// Example 1: Generate from manual specs
const result = await generateFiles({
featureName: 'getUserList',
methodType: 'GET',
apiUrl: '/api/users',
exampleResponse: JSON.stringify({ users: [], total: 0 }),
params: '',
hookType: 'useQuery'
});
console.log(result.model); // TypeScript interfaces
console.log(result.api); // API function
console.log(result.queryKey); // Query key factory
console.log(result.hook); // React Query hook
// Example 2: Generate from OpenAPI spec
const openApiSpec = await parseOpenApiSpec('https://api.example.com/openapi.json');
// Process spec and generate hooks for specific operations
// Example 3: Format generated code
const formatted = await formatCode(result.hook, '/path/to/workspace');API Reference
generateFiles(props: GenerateFilesProps): Promise<GenerateFileResponse>
Generates all parts (model, api, queryKey, hook) for a single endpoint.
Parameters:
featureName: string - Name of the feature (e.g., 'getUserList')methodType: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'apiUrl: string - API endpoint URLexampleResponse: string - JSON string of example responseparams: string - JSON string of params/payloadhookType: 'useQuery' | 'useMutation' | 'useInfiniteQuery'responseSchema?: string - Optional response schemaparamsSchema?: string - Optional params schema
Returns: Object with model, api, queryKey, and hook strings
parseOpenApiSpec(urlOrContent: string): Promise<OpenAPI.Document>
Parses an OpenAPI specification from URL or JSON string.
formatCode(code: string, workspacePath?: string): Promise<string>
Formats TypeScript code using Prettier.
Requirements
- VS Code
^1.90.0 - A project using
react-query(TanStack Query) andaxios. generated code assumes standardaxiosandreact-queryimports.
Extension Settings
This extension currently does not contribute any global settings. It relies on interaction during generation to determine file paths.
Known Issues
- The extension assumes a standard response wrapper pattern (e.g.
{ data: T, success: boolean }) for some heuristic optimizations, but generally supports standard OpenAPI schemas. - Automatic import resolution is currently disabled; you may need to add imports (e.g.,
import { useQuery } from '@tanstack/react-query') to your files manually if they are not already present.
Enjoy faster React Query development!
