2023-10-03 13:08:14 +03:00
|
|
|
import { useQuery } from "@tanstack/react-query";
|
2023-10-02 15:42:23 +03:00
|
|
|
import { useEffect } from "react";
|
|
|
|
import { useTranslation } from "react-i18next";
|
2023-06-27 12:28:09 +03:00
|
|
|
|
2023-10-03 13:08:14 +03:00
|
|
|
import { CHATS_DATA_KEY } from "@/lib/api/chat/config";
|
2023-07-05 19:33:18 +03:00
|
|
|
import { useChatApi } from "@/lib/api/chat/useChatApi";
|
|
|
|
import { useChatsContext } from "@/lib/context/ChatsProvider/hooks/useChatsContext";
|
2024-01-31 23:48:37 +03:00
|
|
|
import { useSupabase } from "@/lib/context/SupabaseProvider";
|
2023-07-05 19:33:18 +03:00
|
|
|
import { useToast } from "@/lib/hooks";
|
2023-06-27 12:28:09 +03:00
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
|
|
export const useChatsList = () => {
|
2023-10-02 15:42:23 +03:00
|
|
|
const { t } = useTranslation(["chat"]);
|
2023-06-27 12:28:09 +03:00
|
|
|
|
2023-12-14 18:22:09 +03:00
|
|
|
const { setAllChats, setIsLoading } = useChatsContext();
|
2023-07-05 19:33:18 +03:00
|
|
|
const { publish } = useToast();
|
|
|
|
const { getChats } = useChatApi();
|
2024-01-31 23:48:37 +03:00
|
|
|
const { session } = useSupabase();
|
2023-07-05 19:33:18 +03:00
|
|
|
|
2023-10-03 13:08:14 +03:00
|
|
|
const fetchAllChats = async () => {
|
2024-01-31 23:48:37 +03:00
|
|
|
if (session) {
|
|
|
|
try {
|
|
|
|
const response = await getChats();
|
|
|
|
|
|
|
|
return response.reverse();
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
publish({
|
|
|
|
variant: "danger",
|
|
|
|
text: t("errorFetching", { ns: "chat" }),
|
|
|
|
});
|
|
|
|
}
|
2023-10-03 13:08:14 +03:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-12-14 18:22:09 +03:00
|
|
|
const { data: chats, isLoading } = useQuery({
|
2023-10-03 13:08:14 +03:00
|
|
|
queryKey: [CHATS_DATA_KEY],
|
|
|
|
queryFn: fetchAllChats,
|
|
|
|
});
|
|
|
|
|
2023-06-27 12:28:09 +03:00
|
|
|
useEffect(() => {
|
2023-10-03 13:08:14 +03:00
|
|
|
setAllChats(chats ?? []);
|
|
|
|
}, [chats]);
|
2023-12-14 18:22:09 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setIsLoading(isLoading);
|
|
|
|
}, [isLoading]);
|
2023-06-27 12:28:09 +03:00
|
|
|
};
|