2025-12-03 09:32:15 +00:00
|
|
|
"use client";
|
|
|
|
|
|
|
|
|
|
import { baseAPI } from "@/lib/API";
|
2026-02-11 20:45:37 +00:00
|
|
|
import { useLocale } from "next-intl";
|
2025-12-03 09:32:15 +00:00
|
|
|
import { useState, useEffect } from "react";
|
|
|
|
|
|
|
|
|
|
interface FetchState<T> {
|
|
|
|
|
data: T | null;
|
|
|
|
|
loading: boolean;
|
|
|
|
|
error: string | null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useFetch = <T>(
|
|
|
|
|
url: string,
|
|
|
|
|
options?: RequestInit
|
|
|
|
|
): FetchState<T> => {
|
|
|
|
|
const [state, setState] = useState<FetchState<T>>({
|
|
|
|
|
data: null,
|
|
|
|
|
loading: true,
|
|
|
|
|
error: null,
|
|
|
|
|
});
|
|
|
|
|
|
2026-02-11 20:45:37 +00:00
|
|
|
const locale = useLocale();
|
2025-12-03 09:32:15 +00:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const fetchData = async () => {
|
|
|
|
|
try {
|
|
|
|
|
setState((prev) => ({ ...prev, loading: true, error: null }));
|
|
|
|
|
|
|
|
|
|
const response = await fetch(baseAPI + url, {
|
|
|
|
|
headers: {
|
2026-02-11 20:45:37 +00:00
|
|
|
"Accept-Language": locale,
|
2025-12-03 09:32:15 +00:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const result = (await response.json()) as T;
|
|
|
|
|
|
|
|
|
|
setState({
|
|
|
|
|
data: result,
|
|
|
|
|
loading: false,
|
|
|
|
|
error: null,
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
setState({
|
|
|
|
|
data: null,
|
|
|
|
|
loading: false,
|
|
|
|
|
error: error instanceof Error ? error.message : "Unknown error",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
fetchData();
|
2026-02-11 20:45:37 +00:00
|
|
|
}, [url, locale]);
|
2025-12-03 09:32:15 +00:00
|
|
|
|
|
|
|
|
return state;
|
|
|
|
|
};
|