Loading Data with React Router
With React Router, fetching data can be simplified down to this, shorter, code snippet:
import { useLoaderData } from 'react-router-dom';
function Posts() {
const loadedPosts = useLoaderData();
return (
<main>
<h1>Your Posts</h1>
<ul className="posts">
{loadedPosts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</main>
);
}
export default Posts;
export async function loader() {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
if (!response.ok) {
throw new Error('Could not fetch posts');
}
return response;
}
Believe it or not, it really is that much less code than in the examples shown in Chapter 8. Back then, when using useEffect(), separate state slices had to be managed to handle loading and error states as well as the received data...