56 lines
1.9 KiB
TypeScript
56 lines
1.9 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { eventsApi } from '../api/eventsApi';
|
|
import { Event, EventListParams } from '../types/api';
|
|
import { notify } from '@/lib/notify';
|
|
import i18n from '@/i18n';
|
|
import { normalizeData } from '../utils/normalize';
|
|
|
|
export const useEvents = (params: EventListParams) => {
|
|
return useQuery({
|
|
queryKey: ['events', params],
|
|
queryFn: async () => {
|
|
const res = await eventsApi.getEvents(params);
|
|
return { data: normalizeData(res.data), total: res.total };
|
|
},
|
|
});
|
|
};
|
|
|
|
export const useEvent = (id: string) => {
|
|
return useQuery({
|
|
queryKey: ['events', id],
|
|
queryFn: () => eventsApi.getEvent(id), // сырые данные для формы
|
|
enabled: !!id && id !== '-',
|
|
});
|
|
};
|
|
|
|
export const useUpdateEvent = () => {
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: ({ id, data }: { id: string; data: Partial<Event> }) =>
|
|
eventsApi.updateEvent(id, data),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['events'] });
|
|
notify.success(i18n.t('common.entityUpdated'));
|
|
},
|
|
onError: () => notify.error(i18n.t('common.updateError')),
|
|
});
|
|
};
|
|
|
|
export const useDeleteEvent = () => {
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: (id: string) => eventsApi.deleteEvent(id),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['events'] });
|
|
notify.success(i18n.t('common.entityDeleted'));
|
|
},
|
|
onError: () => notify.error(i18n.t('common.deleteError')),
|
|
});
|
|
};
|
|
|
|
export const useEventStats = () => {
|
|
return useQuery({
|
|
queryKey: ['event-stats'],
|
|
queryFn: async () => normalizeData(await eventsApi.getEventStats()),
|
|
});
|
|
}; |