feat(base): add useDeleteRowsMutation with optimistic update

This commit is contained in:
Philipinho
2026-04-18 16:35:00 +01:00
parent 0bbcc7ee30
commit 8d793ec26b
@@ -7,6 +7,7 @@ import {
createRow, createRow,
updateRow, updateRow,
deleteRow, deleteRow,
deleteRows,
listRows, listRows,
reorderRow, reorderRow,
} from "@/features/base/services/base-service"; } from "@/features/base/services/base-service";
@@ -15,6 +16,7 @@ import {
CreateRowInput, CreateRowInput,
UpdateRowInput, UpdateRowInput,
DeleteRowInput, DeleteRowInput,
DeleteRowsInput,
ReorderRowInput, ReorderRowInput,
FilterNode, FilterNode,
SearchSpec, SearchSpec,
@@ -220,6 +222,50 @@ export function useDeleteRowMutation() {
}); });
} }
export function useDeleteRowsMutation() {
const { t } = useTranslation();
return useMutation<void, Error, DeleteRowsInput, RowCacheContext>({
mutationFn: (data) => deleteRows({ ...data, requestId: newRequestId() }),
onMutate: async (variables) => {
await queryClient.cancelQueries({
queryKey: ["base-rows", variables.baseId],
});
const snapshots = queryClient.getQueriesData<
InfiniteData<IPagination<IBaseRow>>
>({ queryKey: ["base-rows", variables.baseId] });
const removeSet = new Set(variables.rowIds);
queryClient.setQueriesData<InfiniteData<IPagination<IBaseRow>>>(
{ queryKey: ["base-rows", variables.baseId] },
(old) => {
if (!old) return old;
return {
...old,
pages: old.pages.map((page) => ({
...page,
items: page.items.filter((row) => !removeSet.has(row.id)),
})),
};
},
);
return { snapshots };
},
onError: (_, __, context) => {
if (context?.snapshots) {
for (const [key, data] of context.snapshots) {
queryClient.setQueryData(key, data);
}
}
notifications.show({
message: t("Failed to delete rows"),
color: "red",
});
},
});
}
export function useReorderRowMutation() { export function useReorderRowMutation() {
const { t } = useTranslation(); const { t } = useTranslation();
return useMutation<void, Error, ReorderRowInput, RowCacheContext>({ return useMutation<void, Error, ReorderRowInput, RowCacheContext>({