Blog>
Snippets

Basic Data Fetching with useQuery

Show how to fetch data from an API and display it in a React Native component using the useQuery hook from React Query.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchPosts = async () => {
    const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return data;
};
This code defines a fetchPosts function using axios to fetch data from a JSONPlaceholder API and is intended to be used with the useQuery hook from React Query for data fetching.
import React from 'react';
import { View, Text } from 'react-native';
import { useQuery } from 'react-query';
import { fetchPosts } from './fetchPosts';

const PostsComponent = () => {
    const { isLoading, error, data } = useQuery('posts', fetchPosts);

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

    return (
        <View>
            {data.map(post => (
                <Text key={post.id}>{post.title}</Text>
            ))}
        </View>
    );
};

export default PostsComponent;
This React Native component uses the useQuery hook to fetch posts using the fetchPosts function. It handles loading, error, and successful data fetching states, rendering a list of post titles.