Custom Date Serialization
Show how to customize serialization of Date objects into URL search parameters with TanStack Router, ensuring the date format is consistent and URL-friendly.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
const dateParamConfig = {
serialize: (date) => date.toISOString().split('T')[0], // Serialize Date to 'YYYY-MM-DD' format
parse: (value) => new Date(value) // Parse from 'YYYY-MM-DD' back to Date
};
const router = createBrowserRouter([
{
path: '/',
element: '<HomePage />',
loader: async ({ params, search }) => {
// Use dateParamConfig for handling date URL search params
const startDate = search.get('start', dateParamConfig);
console.log('Start Date:', startDate);
// Perform loader actions with the parsed date
}
}
]);
This code creates a TanStack Router configuration with a custom serialization for Date objects in URL search parameters. It provides a `dateParamConfig` to serialize Date objects to a 'YYYY-MM-DD' format and parse them back to Date objects from the URL search parameters. This configuration is used in a router instance where a loader function logs the parsed start date.