42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
import { useState } from "react";
|
||
import { API_URL } from "../config/authConstants";
|
||
|
||
export function useCreatePost() {
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState(null);
|
||
const [success, setSuccess] = useState(false);
|
||
|
||
const createAd = async (formData) => { // ← принимаем FormData
|
||
setLoading(true);
|
||
setError(null);
|
||
|
||
try {
|
||
const token = localStorage.getItem("token");
|
||
|
||
const res = await fetch(`${API_URL}/api/v1/posts`, {
|
||
method: "POST",
|
||
headers: {
|
||
// Content-Type НЕ указываем — браузер сам добавит multipart/form-data с boundary
|
||
"Authorization": `Bearer ${token}`,
|
||
},
|
||
body: formData, // ← передаём FormData
|
||
});
|
||
|
||
const data = await res.json(); // ← объявляем ПОСЛЕ await res
|
||
|
||
if (!res.ok) {
|
||
throw new Error(data.message || "Error creating ad");
|
||
}
|
||
|
||
setSuccess(true);
|
||
return data;
|
||
} catch (e) {
|
||
setError(e.message);
|
||
return null;
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
return { createAd, loading, error, success };
|
||
} |