Implementing Loaders for Pre-fetching Data
Show how to use TanStack Router's loader function to pre-fetch data for a route, ensuring the data is available before the component renders.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { fetchDataLoader } from './dataFetchers';
// Define a route with a loader function
const router = createBrowserRouter([
{
path: '/home',
element: <HomePage />, // Your component
loader: fetchDataLoader, // Pre-fetch data function
},
]);
This code snippet imports the necessary functions from 'react-router-dom' and a data fetching function. It then creates a browser router with a single route to '/home'. The 'loader' property is used here to pre-fetch data before rendering the 'HomePage' component, ensuring that the data needed for this route is loaded in advance.
function fetchDataLoader() {
// Implement fetching logic here
return fetch('/api/data')
.then(response => response.json())
.then(data => {
// Return data for use in the component
return data;
});
}
This function 'fetchDataLoader' serves as the loader for the route. It fetches data from a specified API endpoint and returns the JSON response. This data is then preloaded for the route, making it immediately available for the component when the route is activated.