fixed code

This commit is contained in:
SlimusMinus
2026-08-11 00:24:07 +03:00
parent c50b75eece
commit 7f59ee1f38
95 changed files with 3623 additions and 2830 deletions

View File

@@ -1,47 +1,57 @@
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();
// API may return an array directly or a wrapper object like { items: [] } / { content: [] }
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("Не удалось создать чат");
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();
// Normalize: array or wrapper object
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",
@@ -49,7 +59,7 @@ export function useChats() {
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, []);
}, [clearChatUnread]);
return { chats, loading, fetchChats, createOrGetChat, fetchMessages, markAsRead };
return { chats, loading, error, fetchChats, createOrGetChat, fetchMessages, markAsRead };
}