Blog>
Snippets

Conditional Fetching Based on User Interaction

Illustrate how to implement conditional fetching where a query's execution is triggered by a user's specific action, using the `enabled` flag to control when the query should run.
import { useQuery } from 'react-query';
import { fetchUserData } from './api';

function UserProfile({ userId }) {
  // State to control when we want to fetch user data
  const [fetchEnabled, setFetchEnabled] = useState(false);

  const { data, isLoading, error } = useQuery(
    ['userData', userId],
    () => fetchUserData(userId),
    {
      // The query will not automatically run until fetchEnabled is true
      enabled: fetchEnabled
    }
  );

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

  return (
    <div>
      <button onClick={() => setFetchEnabled(true)}>Load User Data</button>
      {data && <div>{data.name}</div>}
    </div>
  );
}
This code example demonstrates how to conditionally fetch data based on user interaction using React Query. Here, the `useQuery` hook is used to fetch user data, but the fetch is controlled by the `enabled` option. Initially, `fetchEnabled` is `false`, preventing the query from automatically running. Clicking the button sets `fetchEnabled` to `true`, enabling the query and fetching the data. This pattern is useful for delaying data fetching until it's explicitly required by the user.