fixed code
This commit is contained in:
38
src/hooks/useMyPosts.jsx
Normal file
38
src/hooks/useMyPosts.jsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
/**
|
||||
* Загружает объявления текущего пользователя по userId.
|
||||
*/
|
||||
export function useMyPosts(userId) {
|
||||
const [myAds, setMyAds] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const loadMyPosts = useCallback(async () => {
|
||||
if (!userId) return;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/v1/posts/${userId}`);
|
||||
if (res.status === 404) {
|
||||
setMyAds([]);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
const data = await res.json();
|
||||
const posts = Array.isArray(data) ? data : (data.items ?? []);
|
||||
const normalizedPosts = posts.map(ad => ({
|
||||
...ad,
|
||||
type: ad.type ? ad.type.toLowerCase() : "loss",
|
||||
}));
|
||||
setMyAds(normalizedPosts);
|
||||
} catch (err) {
|
||||
setError(err.message || "Failed to load your ads");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [userId]);
|
||||
|
||||
return { myAds, loading, error, loadMyPosts };
|
||||
}
|
||||
Reference in New Issue
Block a user