Blog>
Snippets

Handling Complex Data Structures in Search Params with TanStack Router

Provide an example of serializing and deserializing complex data structures in search parameters using TanStack Router's API, focusing on maintaining type safety.
import { createBrowserRouter, createRoutesFromElements, Route } from 'tanstack-router-dom';
import { parse, stringify } from 'query-string';

// Custom serializer and parser
const customSearchParamSerializer = {
  parse: (search) => parse(search, { arrayFormat: 'comma' }),
  stringify: (params) => stringify(params, { arrayFormat: 'comma' })
};

// Define routes with custom search param serializer
const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<App />} loader={async ({ params, location }) => {
      // Using custom parser to deserialize search params
      const searchParams = customSearchParamSerializer.parse(location.search);
      return { searchParams };
    }} />
  ),
  { searchParamsSerializer: customSearchParamSerializer }
);
This code snippet demonstrates the use of TanStack Router with a custom search parameter serializer/parser for handling complex data structures like arrays. The 'query-string' library is used for the serialization and deserialization processes, allowing arrays to be represented in the comma format. The custom serializer/parser is then applied to the entire router, ensuring that every route can automatically serialize and deserialize search parameters in the specified format.
import { useSearchParam } from 'tanstack-router-dom';

function useComplexSearchParams() {
  const rawFilter = useSearchParam('filter') || '';
  const filters = rawFilter ? JSON.parse(rawFilter) : [];

  const setFilters = (newFilters) => {
    // Serialize complex data structure to string
    const serializedFilters = JSON.stringify(newFilters);
    // Update search param
    return `/search?filter=${encodeURIComponent(serializedFilters)}`;
  };

  return [filters, setFilters];
}
This code snippet shows how to create a custom hook, `useComplexSearchParams`, using TanStack Router's `useSearchParam` hook to work with complex search parameters such as an array of filters. It demonstrates deserializing a search parameter into a complex JavaScript object and serializing it back into a string for use in the query string. This custom hook encapsulates the process of parsing and stringifying, making it easy to manage complex search parameters within components.