SurfSense/surfsense_web/atoms/chats/chat-mutations.atom.ts

38 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-11-12 14:12:07 +02:00
import { atomWithMutation } from "jotai-tanstack-query";
2025-11-12 16:22:30 +02:00
import { deleteChat } from "@/lib/apis/chats.api";
import { activeSearchSpaceIdAtom } from "../seach-spaces/seach-space-queries.atom";
2025-11-12 14:12:07 +02:00
import { queryClient } from "@/lib/query-client/client";
import { cacheKeys } from "@/lib/query-client/cache-keys";
import { toast } from "sonner";
2025-11-12 14:15:46 +02:00
import { Chat } from "@/app/dashboard/[search_space_id]/chats/chats-client";
2025-11-12 14:12:07 +02:00
export const deleteChatMutationAtom = atomWithMutation((get) => {
2025-11-14 00:42:19 +02:00
const searchSpaceId = get(activeSearchSpaceIdAtom);
const authToken = localStorage.getItem("surfsense_bearer_token");
2025-11-12 14:12:07 +02:00
2025-11-14 00:42:19 +02:00
return {
mutationKey: cacheKeys.activeSearchSpace.chats(searchSpaceId ?? ""),
enabled: !!searchSpaceId && !!authToken,
mutationFn: async (chatId: number) => {
if (!authToken) {
throw new Error("No authentication token found");
}
if (!searchSpaceId) {
throw new Error("No search space id found");
}
2025-11-12 14:12:07 +02:00
2025-11-14 00:42:19 +02:00
return deleteChat(chatId, authToken);
},
2025-11-12 14:12:07 +02:00
2025-11-14 00:42:19 +02:00
onSuccess: (_, chatId) => {
toast.success("Chat deleted successfully");
queryClient.setQueryData(
cacheKeys.activeSearchSpace.chats(searchSpaceId!),
(oldData: Chat[]) => {
return oldData.filter((chat) => chat.id !== chatId);
}
);
},
};
2025-11-12 14:12:07 +02:00
});