Blog>
Snippets

Debugging Masked Routes in TanStack Router

Provide a brief guide on common strategies for debugging issues in masked routes, such as incorrect path parameters or misconfigured route patterns, including how to use console logs effectively within route components.
import { createBrowserRouter, RouterProvider } from 'tanstack/react-router-dom';

// Define a route with a dynamic segment
const router = createBrowserRouter([
  {
    path: 'user/:userId',
    element: '<UserComponent />',
    loader: async ({ params }) => {
      console.log('Loading user with ID:', params.userId);
      // Fetch user data based on userId
      // Placeholder for actual data fetching
      return fetchUserById(params.userId);
    }
  }
]);

// In your app component
function App() {
  return <RouterProvider router={router} />;
}
This code snippet creates a TanStack Router with a dynamic segment for user IDs. It uses a loader to fetch user data, logging the user ID to the console for debugging.
function fetchUserById(userId) {
  console.log(`Fetching user data for ID: ${userId}`);
  // Placeholder for actual fetch call
  // Replace this with your actual data fetching logic
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({name: 'John Doe', id: userId});
    }, 1000);
  });
}
This function simulates fetching user data by ID. It logs the ID being fetched for debugging purposes and returns a promise that resolves with mock data.
function UserComponent() {
  const user = useLoaderData();
  console.log('Loaded user data:', user);

  return (
    <div>
      <h1>User Details</h1>
      <p>Name: {user.name}</p>
      <p>ID: {user.id}</p>
    </div>
  );
}
This presents a component for displaying user details. It logs loaded user data for debugging and displays the user's name and ID.