Files
nahodka-front/src/hooks/useDeletePost.js
SlimusMinus 7f59ee1f38 fixed code
2026-08-11 00:24:07 +03:00

46 lines
1.5 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 { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
/**
* useDeletePost — хук для удаления объявления.
*
* deletePost возвращает { success, error } вместо голого boolean — так
* вызывающий код получает актуальный текст ошибки сразу, без риска прочитать
* устаревшее значение error state до его обновления React'ом.
*
* @returns {Object} { deletePost, loading, error }
*/
export function useDeletePost() {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const deletePost = useCallback(async (postId) => {
setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/posts/${postId}`, {
method: "DELETE",
});
if (!res.ok) {
let body;
try { body = await res.json(); } catch { body = null; }
throw new Error(body?.message || t('post.deleteErrorWithStatus', { status: res.status }));
}
return { success: true, error: null };
} catch (err) {
const message = err.message || t('post.deleteError');
setError(message);
return { success: false, error: message };
} finally {
setLoading(false);
}
}, [t]);
return { deletePost, loading, error };
}