added files in git
This commit is contained in:
62
src/hooks/useChats.js
Normal file
62
src/hooks/useChats.js
Normal 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 };
|
||||
}
|
||||
Reference in New Issue
Block a user