Blog>
Snippets

Dynamic QueryKeys with Array Syntax

Show how to construct a QueryKey using array syntax to dynamically fetch data based on user ID.
import { useQuery } from 'react-query';

function fetchUserData(userId) {
  // Fetch user data from an API
  return fetch(`https://api.example.com/users/${userId}`)
    .then(response => response.json());
}
Defines a function to fetch user data from an API based on a given user ID.
const UserDataComponent = ({ userId }) => {
  const { data, error, isLoading, isError } = useQuery(
    ['userData', userId], // Dynamic QueryKey based on userId
    () => fetchUserData(userId), // Query function
    { enabled: !!userId } // Only fetch when userId is not null
  );

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error.message}</div>;

  // Render user data
  return (
    <div>
      <h1>User Data for ID: {userId}</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};
Uses the useQuery hook from React Query to fetch user data dynamically based on the passed userId. The QueryKey is constructed dynamically as an array, including a 'userData' string and the userId variable, ensuring that the query is refetched whenever the userId changes.