95 lines
2.5 KiB
TypeScript
95 lines
2.5 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { {{ENTITY_LOWER}}Service } from '@/services/{{ENTITY_LOWER}}';
|
|
import type { {{ENTITY}}, Create{{ENTITY}}Request } from '@/types';
|
|
|
|
/**
|
|
* Hook to fetch a {{ENTITY_LOWER}} by ID
|
|
*
|
|
* @param {{ENTITY_LOWER}}Id - The ID of the {{ENTITY_LOWER}} to fetch
|
|
* @returns Query result with {{ENTITY_LOWER}} data
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const { data: {{ENTITY_LOWER}}, isLoading, error } = use{{ENTITY}}('123');
|
|
* ```
|
|
*/
|
|
export function use{{ENTITY}}({{ENTITY_LOWER}}Id: string) {
|
|
return useQuery({
|
|
queryKey: ['{{ENTITY_LOWER}}', {{ENTITY_LOWER}}Id],
|
|
queryFn: () => {{ENTITY_LOWER}}Service.get{{ENTITY}}({{ENTITY_LOWER}}Id),
|
|
enabled: !!{{ENTITY_LOWER}}Id,
|
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hook to create a new {{ENTITY_LOWER}}
|
|
*
|
|
* @returns Mutation function to create {{ENTITY_LOWER}}
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const create{{ENTITY}} = useCreate{{ENTITY}}();
|
|
*
|
|
* const handleCreate = async () => {
|
|
* await create{{ENTITY}}.mutateAsync({
|
|
* // ... request data
|
|
* });
|
|
* };
|
|
* ```
|
|
*/
|
|
export function useCreate{{ENTITY}}() {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (request: Create{{ENTITY}}Request) =>
|
|
{{ENTITY_LOWER}}Service.create{{ENTITY}}(request),
|
|
onSuccess: () => {
|
|
// Invalidate and refetch {{ENTITY_LOWER}} list
|
|
queryClient.invalidateQueries({ queryKey: ['{{ENTITY_LOWER}}s'] });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hook to update a {{ENTITY_LOWER}}
|
|
*
|
|
* @returns Mutation function to update {{ENTITY_LOWER}}
|
|
*/
|
|
export function useUpdate{{ENTITY}}() {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: ({ id, data }: { id: string; data: Partial<{{ENTITY}}> }) =>
|
|
{{ENTITY_LOWER}}Service.update{{ENTITY}}(id, data),
|
|
onSuccess: (_, variables) => {
|
|
// Invalidate specific {{ENTITY_LOWER}} and list
|
|
queryClient.invalidateQueries({ queryKey: ['{{ENTITY_LOWER}}', variables.id] });
|
|
queryClient.invalidateQueries({ queryKey: ['{{ENTITY_LOWER}}s'] });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hook to delete a {{ENTITY_LOWER}}
|
|
*
|
|
* @returns Mutation function to delete {{ENTITY_LOWER}}
|
|
*/
|
|
export function useDelete{{ENTITY}}() {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: (id: string) => {{ENTITY_LOWER}}Service.delete{{ENTITY}}(id),
|
|
onSuccess: () => {
|
|
// Invalidate {{ENTITY_LOWER}} list
|
|
queryClient.invalidateQueries({ queryKey: ['{{ENTITY_LOWER}}s'] });
|
|
},
|
|
});
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|