add auth
This commit is contained in:
@ -69,3 +69,57 @@ export function useDeleteIdea() {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useReorderIdeas() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (items: { id: string; order: number }[]) =>
|
||||
ideasApi.reorder(items),
|
||||
onMutate: async (items) => {
|
||||
// Получаем актуальное состояние store
|
||||
const { filters, sorting, pagination } = useIdeasStore.getState();
|
||||
|
||||
// Отменяем исходящие запросы чтобы не перезаписать оптимистичное обновление
|
||||
await queryClient.cancelQueries({ queryKey: [QUERY_KEY] });
|
||||
|
||||
// Сохраняем предыдущее состояние для отката
|
||||
const queryKey = [QUERY_KEY, { ...filters, ...sorting, ...pagination }];
|
||||
const previousData = queryClient.getQueryData(queryKey);
|
||||
|
||||
// Оптимистично обновляем кэш
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
(
|
||||
old:
|
||||
| { data: { id: string; order: number }[]; meta: unknown }
|
||||
| undefined,
|
||||
) => {
|
||||
if (!old) return old;
|
||||
|
||||
// Создаём новый порядок на основе items
|
||||
const orderMap = new Map(items.map((item) => [item.id, item.order]));
|
||||
const newData = [...old.data].sort((a, b) => {
|
||||
const orderA = orderMap.get(a.id) ?? a.order;
|
||||
const orderB = orderMap.get(b.id) ?? b.order;
|
||||
return orderA - orderB;
|
||||
});
|
||||
|
||||
return { ...old, data: newData };
|
||||
},
|
||||
);
|
||||
|
||||
return { previousData, queryKey };
|
||||
},
|
||||
onError: (_err, _items, context) => {
|
||||
// Откатываем к предыдущему состоянию при ошибке
|
||||
if (context?.previousData) {
|
||||
queryClient.setQueryData(context.queryKey, context.previousData);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
// Инвалидируем для синхронизации с сервером
|
||||
void queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user