56 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-08-05 12:35:40 +07:00
import { useQuery } from '@tanstack/react-query'
2025-08-05 14:34:36 +07:00
import { Products } from '../../types/services/product'
2025-08-05 12:35:40 +07:00
import { api } from '../api'
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-05 12:35:40 +07:00
export const useProductsQuery = {
2025-08-05 14:34:36 +07:00
getProducts: (params: ProductsQueryParams = {}) => {
const { page = 1, limit = 10, search = '', ...filters } = params
2025-08-05 12:35:40 +07:00
return useQuery<Products>({
2025-08-05 14:34:36 +07:00
queryKey: ['products', { page, limit, search, ...filters }],
2025-08-05 12:35:40 +07:00
queryFn: async () => {
2025-08-05 14:34:36 +07:00
const queryParams = new URLSearchParams()
queryParams.append('page', page.toString())
queryParams.append('limit', limit.toString())
if (search) {
queryParams.append('search', search)
}
// Add other filters
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
queryParams.append(key, value.toString())
}
})
const res = await api.get(`/products?${queryParams.toString()}`)
2025-08-05 12:35:40 +07:00
return res.data.data
2025-08-05 14:34:36 +07:00
},
2025-08-06 03:57:45 +07:00
})
},
getProductById: (id: string) => {
return useQuery({
queryKey: ['product', id],
queryFn: async ({ queryKey: [, id] }) => {
const res = await api.get(`/products/${id}`)
return res.data.data
},
2025-08-05 14:34:36 +07:00
// Cache for 5 minutes
staleTime: 5 * 60 * 1000
2025-08-05 12:35:40 +07:00
})
}
}