43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import {useState, useEffect, useCallback} from "react";
|
|
|
|
const API_BASE_URL = "http://192.168.29.174:3000";
|
|
|
|
export const fetchAPI = async (url: string, options?: RequestInit) => {
|
|
try {
|
|
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}${url}`, options);
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error("Fetch error:", error instanceof Error ? error.message : error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export const useFetch = <T>(url: string, options?: RequestInit) => {
|
|
const [data, setData] = useState<T | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const fetchData = useCallback(async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const result = await fetchAPI(url, options);
|
|
setData(result.data);
|
|
} catch (err) {
|
|
setError((err as Error).message);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [url, options]);
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, [fetchData]);
|
|
|
|
return {data, loading, error, refetch: fetchData};
|
|
};
|