Blog>
Snippets

Fetching Data with useQuery Custom Hook

Show how to create a custom hook using the useQuery hook from React Query to fetch a list of posts from an API and return the loading, error, and data states.
import { useQuery } from 'react-query';
import axios from 'axios';
Import necessary modules from react-query and axios for making HTTP requests.
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts?_limit=10');
  return data;
};
Define an asynchronous function 'fetchPosts' to fetch posts from the API. It uses axios to make the GET request.
export const useFetchPosts = () => {
  return useQuery('posts', fetchPosts);
};
Create a custom hook 'useFetchPosts' that uses the useQuery hook from React Query to fetch posts using the 'fetchPosts' function. The first argument to useQuery is the query key ('posts'), and the second is the fetch function. This hook returns the states managed by React Query, such as isLoading, isError, data, etc.