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

How to use the react-query result inside the QueryOptions

1个答案

1

When using React Query, QueryOptions is a key configuration object that enables developers to customize query behavior. For instance, you can configure cache duration and retry strategies via QueryOptions. Next, I will detail how to utilize React Query's return results within QueryOptions and provide a specific example.

Basic Concepts

First, React Query executes asynchronous queries using the useQuery hook and accepts several parameters:

  1. queryKey: A unique identifier used for caching and retrieving query results.
  2. queryFn: A function used to execute asynchronous requests.
  3. options: An optional configuration object, i.e., QueryOptions, used to customize query behavior.

Using QueryOptions

QueryOptions provides numerous useful configuration options, such as:

  • enabled: Controls whether the query is enabled.
  • retry: Sets the number of retries on failure.
  • staleTime: Defines the duration after which data becomes stale.
  • cacheTime: Specifies the duration for which unused cached data remains in memory.
  • onSuccess and onError: Callback functions executed upon query success or failure, respectively.
  • select: Allows transforming or selectively returning the query results.

Example

Suppose we have an API to fetch user information, and we want to fetch and display this data using React Query, executing a callback after the data successfully loads. Here is how to implement this with code:

jsx
import { useQuery } from 'react-query'; function fetchUserData(userId) { return fetch(`https://api.example.com/users/${userId}`) .then(res => res.json()); } function UserProfile({ userId }) { const { data, error, isLoading, isError } = useQuery(['user', userId], () => fetchUserData(userId), { enabled: userId !== null, // Only execute the query when userId is not null retry: 2, // Automatically retry 2 times on failure staleTime: 30000, // Data becomes stale after 30 seconds cacheTime: 300000, // Cached data expires after 5 minutes onSuccess: (data) => { console.log('Data loaded successfully:', data); }, onError: (error) => { console.error('Error loading data:', error); }, select: data => ({ name: data.name, email: data.email }) // Select only the name and email fields from the returned data }); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error: {error.message}</div>; return ( <div> <h1>{data.name}</h1> <p>Email: {data.email}</p> </div> ); } export default UserProfile;

Conclusion

Through this example, we can see how QueryOptions is used within React Query to precisely control query behavior and handle the returned results. This not only makes the code more readable but also enhances functionality flexibility and application efficiency. By properly configuring these options, React Query can significantly simplify the complexity of data fetching and state management.

2024年6月29日 12:07 回复

你的答案