2026-06-03 06:35:03 +02:00
|
|
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
|
|
|
import { productsApi } from "@/lib/api";
|
|
|
|
|
import type { ProductCreate, ProductUpdate } from "@/types";
|
|
|
|
|
|
|
|
|
|
export const productKeys = {
|
|
|
|
|
all: ["products"] as const,
|
|
|
|
|
lists: () => [...productKeys.all, "list"] as const,
|
|
|
|
|
details: () => [...productKeys.all, "detail"] as const,
|
|
|
|
|
detail: (id: string) => [...productKeys.details(), id] as const,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export function useProducts() {
|
2026-06-29 05:38:21 +02:00
|
|
|
return useQuery({
|
|
|
|
|
queryKey: productKeys.lists(),
|
|
|
|
|
queryFn: () => productsApi.list(),
|
|
|
|
|
staleTime: 60000,
|
|
|
|
|
});
|
2026-06-03 06:35:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useProduct(id: string) {
|
2026-06-29 05:38:21 +02:00
|
|
|
return useQuery({
|
|
|
|
|
queryKey: productKeys.detail(id),
|
|
|
|
|
queryFn: () => productsApi.get(id),
|
|
|
|
|
enabled: !!id,
|
|
|
|
|
});
|
2026-06-03 06:35:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useCreateProduct() {
|
|
|
|
|
const qc = useQueryClient();
|
|
|
|
|
return useMutation({
|
|
|
|
|
mutationFn: (p: ProductCreate) => productsApi.create(p),
|
|
|
|
|
onSuccess: () => qc.invalidateQueries({ queryKey: productKeys.lists() }),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useUpdateProduct() {
|
|
|
|
|
const qc = useQueryClient();
|
|
|
|
|
return useMutation({
|
2026-06-29 05:38:21 +02:00
|
|
|
mutationFn: ({ id, patch }: { id: string; patch: ProductUpdate }) =>
|
|
|
|
|
productsApi.update(id, patch),
|
2026-06-03 06:35:03 +02:00
|
|
|
onSuccess: (_d, v) => {
|
|
|
|
|
qc.invalidateQueries({ queryKey: productKeys.lists() });
|
|
|
|
|
qc.invalidateQueries({ queryKey: productKeys.detail(v.id) });
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useDeleteProduct() {
|
|
|
|
|
const qc = useQueryClient();
|
|
|
|
|
return useMutation({
|
|
|
|
|
mutationFn: (id: string) => productsApi.delete(id),
|
|
|
|
|
onSuccess: () => qc.invalidateQueries({ queryKey: productKeys.lists() }),
|
|
|
|
|
});
|
|
|
|
|
}
|