"use client";
import { useState, useEffect } from "react";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export function useFetchData(
url: string,
method: HttpMethod = "GET",
body?: any
) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let isMounted = true;
const fetchData = async () => {
try {
const options: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
},
};
if (body && method !== "GET") {
options.body = JSON.stringify(body);
}
const res = await fetch(url, options);
if (!res.ok) {
console.log("Fetch error:", res.status, res.statusText);
throw new Error(`Erreur API : ${res.status} : ${res.statusText}`);
}
const json = await res.json();
if (isMounted) {
setData(json);
}
} catch (err: any) {
if (isMounted) setError(err.message);
} finally {
if (isMounted) setLoading(false);
}
};
fetchData();
return () => {
isMounted = false;
};
}, [url, method, body]);
return { data, error, loading };
}
///
"use client";
import Card from "@/components/Card";
import { useFetchData } from "@/hooks/runToApi";
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "";
export default function HomePage() {
const { data, error, loading } = useFetchData(apiUrl);
if (loading) return Chargement...
;
if (error) return Erreur : {error}
;
return (
{
data && data.map((item: any) => (
))}
);
}