added get and create posts with back
This commit is contained in:
42
src/hooks/useCreatePost.js
Normal file
42
src/hooks/useCreatePost.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useState } from "react";
|
||||
import { API_URL } from "../config/constants";
|
||||
|
||||
export function useCreatePost() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const createAd = async (adData) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
const res = await fetch(`${API_URL}/api/v1/posts`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(adData),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.message || "Ошибка при создании объявления");
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
return data; // возвращает созданное объявление
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { createAd, loading, error, success };
|
||||
}
|
||||
Reference in New Issue
Block a user