Blog>
Snippets

Basic Usage of QueryKeys for Data Fetching

Demonstrate how to use a simple string as a QueryKey to fetch user data with React Query.
import { useQuery } from 'react-query';

// Fetch user data function
const fetchUserData = async () => {
    const response = await fetch('https://api.example.com/user');
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
};

export function UserComponent() {
    // Using a simple string as a QueryKey
    const { data, error, isLoading } = useQuery('userData', fetchUserData);

    if (isLoading) return <div>Loading...</div>;
    if (error) return <div>An error has occurred: ' + error.message + '</div>;

    return (
        <div>
            <h1>{data.name}</h1>
            <p>{data.email}</p>
        </div>
    );
}
This code demonstrates the basic usage of React Query for data fetching with a simple string as a QueryKey. It defines a function 'fetchUserData' to fetch user data from an API. The useQuery hook is used to perform the data fetching operation, where 'userData' is the QueryKey. Based on the fetch status, it conditionally renders loading text, an error message, or the fetched user data.