Blog>
Snippets

Validating and Using Path Params in Components

Demonstrate the process of validating path parameters extracted from the URL using TanStack Router and how to safely utilize them in a component to fetch and display dynamic content.
import { useParams } from 'tanstack-router-dom';
import { useEffect, useState } from 'react';

function validateUserId(userId) {
  // Add actual validation logic here
  return !isNaN(userId);
}
Defines a validation function for the user ID path parameter to ensure it meets expected criteria, such as being a number.
function UserDetails() {
  const { userId } = useParams();
  const [userDetails, setUserDetails] = useState(null);

  useEffect(() => {
    if (validateUserId(userId)) {
      // Replace with actual data fetching logic
      fetch(`/api/users/${userId}`)
        .then(response => response.json())
        .then(data => setUserDetails(data));
    } else {
      // Handle invalid user ID scenario
      console.error('Invalid user ID');
    }
  }, [userId]);

  if (!userDetails) return <div>Loading...</div>;

  return (
    <div>
      <h2>User Details</h2>
      <p>Name: {userDetails.name}</p>
      <p>Email: {userDetails.email}</p>
    </div>
  );
}
Utilizes the validated `userId` from the URL to fetch and display user details. Demonstrates fetching data based on the valid path parameter and handling invalid cases gracefully.