The feed card showed the contact button on the user's own ads (isOwner is false in the main feed), and the backend rejects a chat with yourself with 400. The button is now hidden when ad.userId is the current user, and createOrGetChat logs the backend error message. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
94 lines
4.6 KiB
JavaScript
94 lines
4.6 KiB
JavaScript
import { useState, useCallback, useRef } 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([]);
|
||
// Стартуем в состоянии загрузки: иначе самый первый рендер успевает показать
|
||
// "Нет чатов" до того, как эффект выставит loading — список "моргает".
|
||
const [loading, setLoading] = useState(true);
|
||
const [error, setError] = useState("");
|
||
const { updateFromChats, clearChatUnread } = useUnread();
|
||
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
|
||
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
|
||
const requestIdRef = useRef(0);
|
||
|
||
// silent=true — фоновое обновление списка (новое сообщение по WS, удаление
|
||
// чата и т.п.): не трогаем loading, иначе текущий список на миг подменяется
|
||
// экраном загрузки и страница "моргает".
|
||
const fetchChats = useCallback(async ({ silent = false } = {}) => {
|
||
const requestId = ++requestIdRef.current;
|
||
if (!silent) 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();
|
||
if (requestId !== requestIdRef.current) return; // устаревший ответ
|
||
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
|
||
cachePostsFromChats(list);
|
||
setChats(list);
|
||
updateFromChats(list);
|
||
} catch (e) {
|
||
if (requestId !== requestIdRef.current) return;
|
||
setError(e.message || t('chats.fetchError'));
|
||
} finally {
|
||
if (requestId === requestIdRef.current && !silent) 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) {
|
||
// Причину отказа (чат с собой, чужое объявление и т.п.) пишем в консоль,
|
||
// иначе 400 выглядит как необъяснимый сбой
|
||
const body = await res.json().catch(() => null);
|
||
console.warn("createOrGetChat failed:", res.status, body?.message);
|
||
throw new Error(t('chats.createError'));
|
||
}
|
||
const chat = await res.json();
|
||
// Объявление чата берём из ответа бэкенда: если он вернул существующий чат по
|
||
// другому объявлению, postInfo с карточки привязал бы к нему чужую картинку.
|
||
// postInfo — только дополнение (emoji) для того же объявления.
|
||
if (chat.id) {
|
||
const sameAd = postInfo && (chat.post?.id ?? chat.postId) != null
|
||
&& String(chat.post?.id ?? chat.postId) === String(postInfo.id);
|
||
if (chat.post) {
|
||
setPostForChat(chat.id, { ...(sameAd ? postInfo : {}), ...chat.post });
|
||
} else if (sameAd) {
|
||
setPostForChat(chat.id, postInfo);
|
||
}
|
||
}
|
||
return chat;
|
||
}, [t]);
|
||
|
||
const fetchMessages = useCallback(async (chatId) => {
|
||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
|
||
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
|
||
// и только что отправленное сообщение выглядело как потерянное.
|
||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||
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 };
|
||
} |