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";
|
|
|
|
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-07-05 19:33:18 +03:00
|
|
|
const { setAllChats } = useChatsContext();
|
|
|
|
const { publish } = useToast();
|
|
|
|
const { getChats } = useChatApi();
|
|
|
|
|
2023-10-03 13:08:14 +03:00
|
|
|
const fetchAllChats = async () => {
|
|
|
|
try {
|
|
|
|
const response = await getChats();
|
2023-10-04 17:26:56 +03:00
|
|
|
|
|
|
|
return response.reverse();
|
2023-10-03 13:08:14 +03:00
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
publish({
|
|
|
|
variant: "danger",
|
|
|
|
text: t("errorFetching", { ns: "chat" }),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const { data: chats } = useQuery({
|
|
|
|
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-06-27 12:28:09 +03:00
|
|
|
};
|