52 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-08-05 12:35:40 +07:00
import { useQuery } from '@tanstack/react-query'
2025-08-11 13:48:24 +07:00
import { Product, Products } from '../../types/services/product'
2025-08-05 12:35:40 +07:00
import { api } from '../api'
2025-08-11 13:48:24 +07:00
import { ProductRecipe } from '../../types/services/productRecipe'
2025-08-05 12:35:40 +07:00
2025-08-05 14:34:36 +07:00
interface ProductsQueryParams {
page?: number
limit?: number
search?: string
// Add other filter parameters as needed
category_id?: string
is_active?: boolean
}
2025-08-06 14:41:23 +07:00
export function useProducts(params: ProductsQueryParams = {}) {
const { page = 1, limit = 10, search = '', ...filters } = params
2025-08-05 14:34:36 +07:00
2025-08-06 14:41:23 +07:00
return useQuery<Products>({
queryKey: ['products', { page, limit, search, ...filters }],
queryFn: async () => {
const queryParams = new URLSearchParams()
2025-08-05 14:34:36 +07:00
2025-08-06 14:41:23 +07:00
queryParams.append('page', page.toString())
queryParams.append('limit', limit.toString())
2025-08-05 14:34:36 +07:00
2025-08-06 14:41:23 +07:00
if (search) {
queryParams.append('search', search)
}
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
queryParams.append(key, value.toString())
2025-08-05 14:34:36 +07:00
}
2025-08-06 14:41:23 +07:00
})
const res = await api.get(`/products?${queryParams.toString()}`)
return res.data.data
},
})
}
2025-08-05 14:34:36 +07:00
2025-08-06 14:41:23 +07:00
export function useProductById(id: string) {
2025-08-11 13:48:24 +07:00
return useQuery<Product>({
2025-08-06 14:41:23 +07:00
queryKey: ['product', id],
queryFn: async () => {
const res = await api.get(`/products/${id}`)
return res.data.data
},
staleTime: 5 * 60 * 1000
})
2025-08-05 12:35:40 +07:00
}