En React, puedes consumir APIs de varias maneras, dependiendo de las necesidades y la complejidad de tu proyecto. Las principales formas son:
Esta guía incluye ejemplos prácticos para cada método, destacando su implementación, ventajas y consideraciones, para que puedas decidir cuál se adapta mejor a tu proyecto.
Fetch API Nativoimport { useState, useEffect } from 'react';
function FetchExample() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchPosts = async () => {
try {
const response = await fetch('https://api.vercel.app/blog');
if (!response.ok) {
throw new Error('Error en la solicitud');
}
const data = await response.json();
setPosts(data);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
fetchPosts();
}, []);
if (loading) return <div>Cargando...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
} npm install axios import { useState, useEffect } from 'react';
import axios from 'axios';
function AxiosExample() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const source = axios.CancelToken.source();
const fetchPosts = async () => {
try {
const response = await axios.get('https://api.vercel.app/blog', {
cancelToken: source.token,
headers: {
'Content-Type': 'application/json'
}
});
setPosts(response.data);
setLoading(false);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Solicitud cancelada');
} else {
setError(error.message);
}
setLoading(false);
}
};
fetchPosts();
// Función de limpieza
return () => {
source.cancel('Componente desmontado');
};
}, []);
if (loading) return <div>Cargando...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
} npm install @tanstack/react-query import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
// Configuración del cliente de Query
const queryClient = new QueryClient();
// Función de fetching
const fetchPosts = async () => {
const response = await fetch('https://api.vercel.app/blog');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
function PostsComponent() {
const {
data: posts,
isLoading,
isError,
error
} = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
staleTime: 5000, // Caché por 5 segundos
refetchOnWindowFocus: true
});
if (isLoading) return <div>Cargando...</div>;
if (isError) return <div>Error: {error.message}</div>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
}
// Envolver la aplicación con QueryClientProvider
function App() {
return (
<QueryClientProvider client={queryClient}>
<PostsComponent />
</QueryClientProvider>
);
} import { useState, useEffect } from 'react';
function useApiData(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Error en la solicitud');
}
const result = await response.json();
setData(result);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
function PostsComponent() {
const {
data: posts,
loading,
error
} = useApiData('https://api.vercel.app/blog');
if (loading) return <div>Cargando...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
} Cada método de consumo de API en React tiene sus propias ventajas: