Blog>
Snippets

Dynamic Route Fetching with TanStack Router

Demonstrate how to fetch and render content for dynamic routes using TanStack Router in a SSR context, focusing on handling params and asynchronous data fetching.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
Imports necessary components and functions from TanStack Router.
async function fetchData(param) {
  // This function simulates fetching data based on a parameter.
  // In a real scenario, replace this with actual data fetching e.g., using fetch or axios
  return Promise.resolve(`Data for ${param}`);
}
Defines an asynchronous function to simulate data fetching based on a dynamic route parameter.
const Post = ({ params }) => {
  const [postData, setPostData] = React.useState('Loading...');
  React.useEffect(() => {
    fetchData(params.postId).then(data => setPostData(data));
  }, [params.postId]);
  return <div>{postData}</div>;
};
Defines a Post component that fetches and displays data based on dynamic route parameters.
const router = createBrowserRouter([
  {
    path: '/posts/:postId',
    element: <Post />,
    loader: async ({ params }) => {
      return fetchData(params.postId);
    }
  }
]);
Creates a router instance with a dynamic route for posts. It uses the loader function to fetch data based on the dynamic parameter `postId`.
function App() {
  return <RouterProvider router={router} />;
}
Defines the main App component that renders the router using RouterProvider.