Publicado el 28 de diciembre de 2024
Server Components allow you to run fetch logic directly on the server. This is the recommended approach for most use cases.
// src/app/posts/page.jsx
import React from 'react';
async function fetchPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
return posts;
}
export default async function Posts() {
const posts = await fetchPosts();
return (
<div>
<h1>List of Posts</h1>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
}For cases where you need to fetch data in response to user actions or need dynamic updates, you can use Client Components with React hooks.
'use client';
import React, { useEffect, useState } from 'react';
const Posts = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
setPosts(data);
setLoading(false);
};
fetchPosts();
}, []);
if (loading) return <p>Loading...</p>;
return (
<div>
<h1>List of Posts</h1>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
};
export default Posts;It is crucial to implement proper error handling when working with APIs:
'use client';
import React, { useEffect, useState } from 'react';
const Posts = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!res.ok) {
throw new Error('Could not get data');
}
const data = await res.json();
setPosts(data);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
fetchPosts();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
// ...render component
);
};