38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import apiClient from '../api/apiClient';
|
|
import { AxiosError } from 'axios';
|
|
|
|
// Definimos la URL de la API en un solo lugar y de forma explícita.
|
|
const API_ROOT = 'https://widgets.eldia.com/api';
|
|
|
|
export function useApiData<T>(endpoint: string) {
|
|
const [data, setData] = useState<T | null>(null);
|
|
const [loading, setLoading] = useState<boolean>(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const fetchData = useCallback(async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
// Construimos la URL completa y absoluta para la llamada.
|
|
const fullUrl = `${API_ROOT}${endpoint}`;
|
|
const response = await apiClient.get<T>(fullUrl);
|
|
setData(response.data);
|
|
} catch (err) {
|
|
if (err instanceof AxiosError) {
|
|
setError(`Error de red o de la API: ${err.message}`);
|
|
} else {
|
|
setError('Ocurrió un error inesperado.');
|
|
}
|
|
console.error(err);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [endpoint]);
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, [fetchData]);
|
|
|
|
return { data, loading, error, refetch: fetchData };
|
|
} |