Blog>
Snippets

Using conditional fetching to prevent unnecessary queries

Illustrate the use of conditions within React Query hooks to prevent unnecessary data fetching based on certain criteria, such as user authentication status.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchUserProfile = async () => {
  const { data } = await axios.get('/api/user/profile');
  return data;
};

const UserProfile = ({ userId }) => {
  const { isLoggedIn } = useAuth(); // Assuming useAuth is a hook that provides auth state

  const { data: userProfile, isLoading, isError } = useQuery(
    ['userProfile', userId],
    fetchUserProfile,
    {
      // Only fetch user profile if the user is logged in
      enabled: isLoggedIn
    }
  );

  if (!isLoggedIn) return <div>Please log in to see user profile.</div>;
  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching user profile.</div>;

  return (
    <div>
      <h2>{userProfile.name}</h2>
      <p>{userProfile.bio}</p>
    </div>
  );
};
This code defines a React component named UserProfile that uses the useQuery hook from React Query to fetch a user's profile data from an API, but only if the user is currently logged in. This is achieved by using the enabled option in the useQuery's options object, setting it to the isLoggedIn state which presumably comes from a useAuth custom hook. If the user is not logged in, it immediately returns a message prompting the user to log in. If the data is being loaded or an error occurs, it handles those states by conditionally rendering loading and error messages, respectively. Once data is successfully fetched and the user is logged in, it displays the user's name and bio.