Blog>
Snippets

Basic React Query Data Fetching

Demonstrate how to use React Query's useQuery hook for fetching data and displaying it in a component.
import { useQuery } from 'react-query';
import axios from 'axios';

// Define the fetch function
const fetchPosts = async () => {
    const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return data;
};

// React component using useQuery hook to fetch and display data
function PostsComponent() {
    const { isLoading, error, data } = useQuery('posts', fetchPosts);

    if (isLoading) return 'Loading...';

    if (error) return 'An error has occurred: ' + error.message;

    return (
        <ul>
            {data.map(post => (
                <li key={post.id}>{post.title}</li>
            ))}
        </ul>
    );
}
This code imports the useQuery hook from react-query and axios for making HTTP requests. It defines a fetchPosts function to fetch data from a placeholder API. Then, it creates a PostsComponent that uses the useQuery hook to fetch the posts data. The hook manages the loading state, error handling, and the data state. Based on the state, the component renders a loading message, an error message, or a list of posts.