Loading Data with React Router
With React Router, the example from the previous chapter can be simplified down to this 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 previous example. Though, to be fair, the content that should be displayed in case of an error is missing here. It's in a separate file (which will be shown later...