added files in git

This commit is contained in:
SlimusMinus
2026-07-03 00:04:56 +03:00
parent a5d457b07a
commit b924bc5f94
33 changed files with 2916 additions and 2 deletions

62
src/hooks/useChats.js Normal file
View File

@@ -0,0 +1,62 @@
import { useState, useCallback } from "react";
import { API_URL } from "../config/authConstants";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
function authHeaders() {
return {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("token")}`,
};
}
export function useChats() {
const [chats, setChats] = useState([]);
const [loading, setLoading] = useState(false);
const fetchChats = useCallback(async () => {
setLoading(true);
try {
const res = await fetch(`${API_URL}/api/v1/chats`, { headers: authHeaders() });
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);
} finally {
setLoading(false);
}
}, []);
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 fetch(url, { method: "POST", headers: authHeaders() });
if (!res.ok) throw new Error("Не удалось создать чат");
const chat = await res.json();
if (postInfo && chat.id) {
setPostForChat(chat.id, postInfo);
}
return chat;
}, []);
const fetchMessages = useCallback(async (chatId) => {
const res = await fetch(`${API_URL}/api/v1/chats/${chatId}/messages`, { headers: authHeaders() });
const data = await res.json();
// Normalize: array or wrapper object
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}, []);
const markAsRead = useCallback(async (chatId) => {
try {
await fetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
headers: authHeaders(),
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, []);
return { chats, loading, fetchChats, createOrGetChat, fetchMessages, markAsRead };
}