Blog>
Snippets

Leveraging Loaders for Dynamic Route Data Fetching

Illustrate how to use loaders within TanStack Router to dynamically fetch data for routes based on parameters or path changes, emphasizing the use of async/await for data fetching before the component renders.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router-dom';
import UserProfile from './components/UserProfile';

// Define the router
const router = createBrowserRouter([
  {
    path: 'user/:userId',
    element: <UserProfile />, // Component to render
    loader: async ({ params }) => {
      // Fetch user data based on the `userId` parameter
      const response = await fetch(`https://api.example.com/users/${params.userId}`);
      const userData = await response.json();
      return { userData }; // This object is passed as props to the `UserProfile` component
    },
  },
]);
This code snippet defines a route for a user profile in a TanStack Router setup. The `loader` function is used to fetch user data asynchronously based on a `userId` parameter from the URL path. The fetched data is then passed as props to the `UserProfile` component that is rendered for this route.