Files
nahodka-front/src/hooks/useChats.js
SlimusMinus 7f59ee1f38 fixed code
2026-08-11 00:24:07 +03:00

65 lines
2.2 KiB
JavaScript

import { useState, useCallback } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
import { useUnread } from "../context/UnreadContext";
export function useChats() {
const { t } = useTranslation();
const [chats, setChats] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const { updateFromChats, clearChatUnread } = useUnread();
const fetchChats = useCallback(async () => {
setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/chats`);
if (!res.ok) throw new Error(t('chats.fetchError'));
const data = await res.json();
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
cachePostsFromChats(list);
setChats(list);
updateFromChats(list);
} catch (e) {
setError(e.message || t('chats.fetchError'));
} finally {
setLoading(false);
}
}, [updateFromChats, t]);
const createOrGetChat = useCallback(async (otherUserId, postId, postInfo) => {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}`);
if (postId) url.searchParams.set("postId", postId);
const res = await apiFetch(url, { method: "POST" });
if (!res.ok) throw new Error(t('chats.createError'));
const chat = await res.json();
if (postInfo && chat.id) {
setPostForChat(chat.id, postInfo);
}
return chat;
}, [t]);
const fetchMessages = useCallback(async (chatId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}, []);
const markAsRead = useCallback(async (chatId) => {
clearChatUnread(chatId);
try {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, [clearChatUnread]);
return { chats, loading, error, fetchChats, createOrGetChat, fetchMessages, markAsRead };
}