52 lines
1.8 KiB
JavaScript
52 lines
1.8 KiB
JavaScript
// src/hooks/useDeleteChat.js
|
||
import { useState, useCallback } from "react";
|
||
import { useTranslation } from 'react-i18next';
|
||
import { API_URL } from "../config/authConstants";
|
||
import { apiFetch } from "../api/apiClient";
|
||
import { useUnread } from "../context/UnreadContext";
|
||
import { removePostForChat } from "../stores/chatPostStore";
|
||
|
||
/**
|
||
* useDeleteChat — хук для удаления чата.
|
||
*
|
||
* deleteChat возвращает { success, error } вместо голого boolean — так
|
||
* вызывающий код получает актуальный текст ошибки сразу, без риска прочитать
|
||
* устаревшее значение error state до его обновления React'ом (тот же паттерн,
|
||
* что в useDeletePost/usePostStatus).
|
||
*
|
||
* @returns {Object} { deleteChat, loading, error }
|
||
*/
|
||
export function useDeleteChat() {
|
||
const { t } = useTranslation();
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState("");
|
||
const { clearChatUnread } = useUnread();
|
||
|
||
const deleteChat = useCallback(async (chatId) => {
|
||
setLoading(true);
|
||
setError("");
|
||
try {
|
||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}`, {
|
||
method: "DELETE",
|
||
});
|
||
|
||
if (!res.ok) {
|
||
let body;
|
||
try { body = await res.json(); } catch { body = null; }
|
||
throw new Error(body?.message || t('chats.deleteErrorWithStatus', { status: res.status }));
|
||
}
|
||
|
||
clearChatUnread(chatId);
|
||
removePostForChat(chatId);
|
||
return { success: true, error: null };
|
||
} catch (err) {
|
||
const message = err.message || t('chats.deleteError');
|
||
setError(message);
|
||
return { success: false, error: message };
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}, [t, clearChatUnread]);
|
||
|
||
return { deleteChat, loading, error };
|
||
} |