46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
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 };
|
||
} |