Blog>
Snippets

Fetching Data with useQuery Hook based on Route Parameters

Showcase how to use the useQuery hook from React Query to fetch data based on dynamic parameters obtained from TanStack Router's useMatch hook, handling loading and error states.
import { useMatch } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
Importing necessary hooks from TanStack Router for matching routes and from React Query for data fetching.
const UserDetails = () => {
  // Fetching dynamic route parameter using useMatch
  const match = useMatch('/users/:userId');
  const userId = match?.params.userId;
Component to display user details. Using `useMatch` to extract dynamic route parameter `userId`.
const fetchUser = async ({ queryKey }) => {
  const [_key, { userId }] = queryKey;
  const response = await fetch(`https://api.example.com/users/${userId}`);
  if (!response.ok) throw new Error('Network response was not ok.');
  return response.json();
};
Function to fetch user data. It takes queryKey as argument, which includes the query's unique key and dynamic parameter `userId`.
const { data, isError, isLoading, error } = useQuery(['user', { userId }], fetchUser, {
  // Options
  enabled: !!userId
});
Using `useQuery` to fetch data based on `userId`. The query is enabled only if `userId` is present.
if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error.message}</div>;
  return (
    <div>
      <h2>{data.name}</h2>
      <p>Email: {data.email}</p>
    </div>
  );
};
Handling loading and error states and rendering user data. The component displays a loading message, error information, or the user's details based on the query state.