Blog>
Snippets

Using TanStack Config to Parse and Validate URL Params on Load

Illustrate how to parse and validate URL query parameters when the application loads, using TanStack Config to ensure initial state correctness.
import { useSearchParams } from 'tanstack-router-dom';

function validateSearchParams(params) {
  // Define the schema for your query params
  const schema = {
    page: value => !isNaN(value) && value > 0,
    filter: value => typeof value === 'string' && value.trim() !== ''
  };

  // Validate each parameter against the schema
  Object.keys(params).forEach(key => {
    if (!schema[key] || !schema[key](params[key])) {
      throw new Error(`Invalid value for query parameter: ${key}`);
    }
  });
}
This piece of code imports the useSearchParams hook from tanstack-router-dom to handle search parameters from the URL. It defines a function validateSearchParams to validate the query parameters against a defined schema. The schema is an object where each key is a query parameter name, and the value is a function that returns true if the parameter value is valid. This code snippet is foundational for setting up query parameter validation on load with TanStack Config.
function useValidatedSearchParams() {
  const [searchParams] = useSearchParams();

  // Parse the search params from the URL
  const params = Object.fromEntries(searchParams.entries());

  try {
    // Validate the search params based on defined criteria
    validateSearchParams(params);
    console.log('Search params are valid:', params);
  } catch (error) {
    console.error('Invalid search params:', error.message);
  }

  return params;
}
This code defines a custom hook useValidatedSearchParams that uses the useSearchParams hook to get the current search parameters from the URL. It then parses these parameters into an object and validates them using the previously defined validateSearchParams function. If the parameters are valid, it logs a success message; otherwise, it catches and logs the validation error. This hook is useful for components that need to load with validated query parameters.