Blog>
Snippets

Dynamic Data Fetching with TanStack Router

Show how to fetch data dynamically based on the active route in a server-side rendered application using TanStack Router.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router-dom';
import { fetchPostData } from './api';

const router = createBrowserRouter([
  {
    path: 'posts/:postId',
    element: '<Post />',
    loader: async ({ params }) => {
      // Fetching post data using the postId param from the route
      const postData = await fetchPostData(params.postId);
      return { postData };
    },
  },
]);
This code snippet initializes a TanStack Router with a dynamic route for blog posts. When the route matches 'posts/:postId', it dynamically loads the Post component and fetches post data based on the 'postId' parameter using a loader function. The 'fetchPostData' function is an example API call that retrieves data for a specific post.
import { useLoaderData } from '@tanstack/react-router-dom';

function Post() {
  const { postData } = useLoaderData();

  return (
    <div>
      <h1>{postData.title}</h1>
      <p>{postData.content}</p>
    </div>
  );
}
Here, the 'Post' component utilizes 'useLoaderData' from TanStack Router to access the data loaded by the loader function in the route configuration. It then renders the post's title and content on the screen. This demonstrates how to consume and display dynamic data based on the active route in a server-side rendered application.