Generate React Query Hook
Create a custom hook using TanStack Query for data fetching.
Important: Follow the Learning Mode guidelines in
_templates/learning-mode.md
Arguments
$ARGUMENTS- Hook name or API endpoint (e.g., "useTasks", "GET /projects/:id")
Pre-flight (BAT BUOC)
Truoc khi tao hook, DOC:
apps/web/src/services/api.ts— confirm Axios instance config- Backend controller tuong ung — confirm endpoint URL + response type
.context/research/PITFALLS.md> React section — TanStack Query cache stale.context/research/CONVENTIONS.md> API Response Format
Instructions
Step 1: Clarify (Query vs Mutation, parameters)
Step 2: Read backend code (KHONG SKIP) — confirm endpoint URL + data shape
Step 3: Create the hook
Query (GET):
typescript1import { useQuery } from '@tanstack/react-query'; 2import { api } from '@/services/api'; 3 4export const use[Name] = (id: string) => { 5 return useQuery({ 6 queryKey: ['[name]', id], 7 queryFn: async () => { 8 const { data } = await api.get<[Type]>(`/[endpoint]/${id}`); 9 return data; 10 }, 11 enabled: !!id, 12 }); 13};
Mutation (POST/PATCH/DELETE):
typescript1import { useMutation, useQueryClient } from '@tanstack/react-query'; 2import { api } from '@/services/api'; 3 4export const use[Name] = () => { 5 const queryClient = useQueryClient(); 6 return useMutation({ 7 mutationFn: async (input: [Type]) => { 8 const { data } = await api.post('/[endpoint]', input); 9 return data; 10 }, 11 onSuccess: () => { 12 queryClient.invalidateQueries({ queryKey: ['[related]'] }); 13 }, 14 }); 15};
Code Standards
- Naming:
use[Action][Resource]—useGetTasks,useCreateProject - Query Keys: Array
['resource', id, params] - API client: LUON dung
@/services/api— KHONG tao Axios instance moi - Types: Match backend DTOs — KHONG tu bia type
- Response: Object truc tiep (khong wrapper), list
{ data, total, page, limit }
Pitfalls
enabled: !!dependencycho dependent queriesinvalidateQueries()sau mutation — tranh stale cache- Destructure dung:
const { data } = await api.get(...)— data la response body
After Completion
Remind user: "Test hook trong component" + "Update PROGRESS.md!"