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

How can I pass a query param as an argument with React Query?

1个答案

1

When using React Query to manage data requests, you can pass query parameters in multiple ways. React Query primarily retrieves data from remote sources using the useQuery hook, where query keys and parameters can be defined flexibly. Below are specific steps and examples for passing query parameters with React Query:

Step 1: Install React Query

First, ensure React Query is installed in your project. If not, install it using npm or yarn:

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

Step 2: Set Up the Query Function

Define a function responsible for initiating network requests, which can use fetch or libraries like axios. For example, define a function to fetch user data that accepts a user ID as a parameter:

javascript
const fetchUserById = 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(); }

Step 3: Pass Parameters Using the useQuery Hook

In the component, use the useQuery hook and include the query parameters (in this example, the user ID) as part of the useQuery key. This enables React Query to differentiate and cache query results based on different parameter values.

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

Step 4: Use in Parent Component

In the parent component, pass the user ID as props to the UserProfile component as needed.

javascript
function App() { const userId = '123'; // Assume this is dynamically obtained return <UserProfile userId={userId} />; }

Summary

By including query parameters within the useQuery call, React Query can effectively differentiate and cache query results based on different parameters, thereby optimizing performance and reducing unnecessary data re-fetches. This approach not only streamlines the data retrieval process but also enhances overall application performance.

2024年8月5日 11:23 回复

你的答案