38 lines
1.1 KiB
JavaScript
38 lines
1.1 KiB
JavaScript
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 };
|
|
} |