乐闻世界logo
搜索文章和话题

How to fetch data with React Query?

1个答案

1

In React applications, React Query is a powerful library for fetching, caching, and updating asynchronous data. Below, I will outline the steps to use React Query for fetching data, illustrated with a simple example.

Step 1: Install React Query

First, install React Query in your React project. You can use npm or yarn:

bash
npm install react-query # or yarn add react-query

Step 2: Set Up React Query Client

In your application, set up a QueryClient and provide it to your React component tree using the QueryClientProvider component. This is typically done in your application's top-level component:

jsx
import { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <MyComponent /> </QueryClientProvider> ); }

Step 3: Use the useQuery Hook to Fetch Data

In React Query, useQuery is a crucial hook for asynchronously fetching data. It requires at least two parameters: a unique key and an asynchronous function to fetch your data.

Suppose we have an API at https://api.example.com/data; we can use useQuery as follows to fetch this API's data:

jsx
import { useQuery } from 'react-query'; function MyComponent() { const { data, error, isLoading } = useQuery('data', fetchMyData); async function fetchMyData() { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); } if (isLoading) return <div>Loading...</div>; if (error) return <div>An error occurred: {error.message}</div>; return ( <div> <h1>Received Data</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }

Summary

The steps above demonstrate how to use React Query in a React application to fetch data. First, install and configure React Query, then use the useQuery hook within components to fetch data. The caching and data synchronization features provided by React Query enable your application to handle data more efficiently, enhancing user experience.

2024年6月29日 12:07 回复

你的答案