Blog>
Snippets

Automatic Conversion of Search Params to JSON with TanStack Router

Demonstrate how TanStack Router automatically converts URL search parameters into a structured JSON object, streamlining state management and improving type safety.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';

// Define the searchParamSchema
const searchParamSchema = {
  searchTerm: '',
  pageSize: 10,
  pageIndex: 0
};

// Create a route with a path and a loader that extracts search params
const router = createBrowserRouter([
  {
    path: '/search',
    loader: async ({ params, searchParams }) => {
      // Convert searchParams to structured JSON based on searchParamSchema
      const queryParams = Object.fromEntries(searchParams);
      return { queryParams };
    }
  }
]);

// Setup the RouterProvider with the created router
function App() {
  return <RouterProvider router={router} />;
}
This code snippet demonstrates how to set up TanStack Router to automatically convert URL search parameters into a structured JSON object according to a predefined schema. It includes creating a router with a route that has a loader function. This function extracts the search parameters from the URL, converts them into a simple key-value object (mimicking structured JSON based on the schema), and returns it for use within the application. The `RouterProvider` is then used to integrate the router into the React app.
// Usage inside a component to access search params
import { useLoaderData } from 'tanstack-router';

function SearchPage() {
  const { queryParams } = useLoaderData();
  console.log('Search Params as Structured JSON:', queryParams);

  // Use the queryParams object for state management, filtering, etc.
  return (
    <div>
      <h1>Search Results</h1>
      {/* Render search results based on queryParams */}
    </div>
  );
}
Here, we show how to utilize the extracted search parameters within a React component. This piece of code fetches the structured JSON `queryParams` object (which was automatically converted by TanStack Router) using `useLoaderData()` hook. It then logs this object, demonstrating that it can be easily used within components for rendering or state management purposes, such as filtering search results based on the criteria encoded in the query parameters.