Files
nahodka-front/src/hooks/useChats.js
2026-08-03 02:44:57 +03:00

55 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useCallback } from "react";
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
export function useChats() {
const [chats, setChats] = useState([]);
const [loading, setLoading] = useState(false);
const fetchChats = useCallback(async () => {
setLoading(true);
try {
const res = await apiFetch(`${API_URL}/api/v1/chats`);
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 apiFetch(url, { method: "POST" });
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 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) => {
try {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, []);
return { chats, loading, fetchChats, createOrGetChat, fetchMessages, markAsRead };
}