38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
// src/hooks/queries/useBrandsQuery.ts
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { fetchAllBrands } from '../../services/apiClient';
|
|
import type { Brand } from '../../types';
|
|
|
|
/**
|
|
* Query hook for fetching all brands (admin feature).
|
|
*
|
|
* @param enabled - Whether the query should run (default: true)
|
|
* @returns TanStack Query result with Brand[] data
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const { data: brands = [], isLoading, error } = useBrandsQuery();
|
|
* ```
|
|
*/
|
|
export const useBrandsQuery = (enabled: boolean = true) => {
|
|
return useQuery({
|
|
queryKey: ['brands'],
|
|
queryFn: async (): Promise<Brand[]> => {
|
|
const response = await fetchAllBrands();
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({
|
|
message: `Request failed with status ${response.status}`,
|
|
}));
|
|
throw new Error(error.message || 'Failed to fetch brands');
|
|
}
|
|
|
|
const json = await response.json();
|
|
// API returns { success: true, data: [...] }, extract the data array
|
|
return json.data ?? json;
|
|
},
|
|
enabled,
|
|
staleTime: 1000 * 60 * 5, // 5 minutes - brands don't change frequently
|
|
});
|
|
};
|