98 lines
No EOL
2.7 KiB
JavaScript
98 lines
No EOL
2.7 KiB
JavaScript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { categoryAdminService } from '../services/categoryAdminService';
|
|
import { useNotification } from './reduxHooks';
|
|
|
|
/**
|
|
* Hook for fetching all categories
|
|
*/
|
|
export const useAdminCategories = () => {
|
|
return useQuery({
|
|
queryKey: ['admin-categories'],
|
|
queryFn: () => categoryAdminService.getAllCategories(),
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Hook for fetching a single category by ID
|
|
*/
|
|
export const useAdminCategory = (id) => {
|
|
return useQuery({
|
|
queryKey: ['admin-category', id],
|
|
queryFn: () => categoryAdminService.getCategoryById(id),
|
|
enabled: !!id,
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Hook for creating a new category
|
|
*/
|
|
export const useCreateCategory = () => {
|
|
const queryClient = useQueryClient();
|
|
const notification = useNotification();
|
|
|
|
return useMutation({
|
|
mutationFn: (categoryData) => categoryAdminService.createCategory(categoryData),
|
|
onSuccess: (data) => {
|
|
queryClient.invalidateQueries({ queryKey: ['admin-categories'] });
|
|
queryClient.invalidateQueries({ queryKey: ['categories'] });
|
|
notification.showNotification('Category created successfully!', 'success');
|
|
return data;
|
|
},
|
|
onError: (error) => {
|
|
notification.showNotification(
|
|
error.message || 'Failed to create category',
|
|
'error'
|
|
);
|
|
throw error;
|
|
},
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Hook for updating a category
|
|
*/
|
|
export const useUpdateCategory = () => {
|
|
const queryClient = useQueryClient();
|
|
const notification = useNotification();
|
|
|
|
return useMutation({
|
|
mutationFn: ({ id, categoryData }) => categoryAdminService.updateCategory(id, categoryData),
|
|
onSuccess: (data) => {
|
|
queryClient.invalidateQueries({ queryKey: ['admin-categories'] });
|
|
queryClient.invalidateQueries({ queryKey: ['categories'] });
|
|
notification.showNotification('Category updated successfully!', 'success');
|
|
return data;
|
|
},
|
|
onError: (error) => {
|
|
notification.showNotification(
|
|
error.message || 'Failed to update category',
|
|
'error'
|
|
);
|
|
throw error;
|
|
},
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Hook for deleting a category
|
|
*/
|
|
export const useDeleteCategory = () => {
|
|
const queryClient = useQueryClient();
|
|
const notification = useNotification();
|
|
|
|
return useMutation({
|
|
mutationFn: (id) => categoryAdminService.deleteCategory(id),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['admin-categories'] });
|
|
queryClient.invalidateQueries({ queryKey: ['categories'] });
|
|
notification.showNotification('Category deleted successfully!', 'success');
|
|
},
|
|
onError: (error) => {
|
|
notification.showNotification(
|
|
error.message || 'Failed to delete category',
|
|
'error'
|
|
);
|
|
throw error;
|
|
},
|
|
});
|
|
}; |