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

How to fetch data from Web API using React query?

1个答案

1

When working with React Query to fetch data from Web APIs, several key concepts and steps are commonly used, including configuration, query setup, and result handling. I will now provide a detailed explanation.

Step 1: Installation and Configuration of React Query

First, install the React Query library in your React project using npm or yarn.

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

After installation, set up a QueryClientProvider at the top level of your application using a QueryClient instance to configure it, providing the React Query environment and configuration throughout your app.

javascript
import { QueryClient, QueryClientProvider } from 'react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> {/* Your application components */} </QueryClientProvider> ); }

Step 2: Creating Queries

React Query uses the useQuery hook to fetch data from the network. This hook requires at least two parameters: a unique key (for caching and tracking query state) and an asynchronous function (typically the function to retrieve data from your API).

Assume we have a function fetchUser that retrieves user information from a Web API:

javascript
const fetchUser = async (userId) => { const response = await fetch(`https://api.example.com/users/${userId}`); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }

Then, use useQuery in your component to fetch data:

javascript
import { useQuery } from 'react-query'; function UserProfile({ userId }) { const { data, error, isLoading, isError } = useQuery(['user', userId], () => fetchUser(userId)); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error: {error.message}</div>; return ( <div> <h1>{data.name}</h1> <p>{data.email}</p> </div> ); }

Step 3: Using Query Results

In the UserProfile component above, we leverage several return values from useQuery:

  • data: Contains the data returned successfully from the API request.
  • error: Contains the error information when the request fails.
  • isLoading: A boolean indicating whether the query is in progress.
  • isError: A boolean indicating whether an error occurred during the query.

These return values can be used within your component to control rendering based on different states, such as loading, error handling, and displaying the final data.

Summary

Using React Query, you can efficiently retrieve data from Web APIs, handle loading states and errors gracefully, and utilize React Query's caching and data synchronization features to improve application performance and user experience.

2024年6月29日 12:07 回复

你的答案