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

How to observe data change in a separate component in react- query ?

1个答案

1

In React Query, a common approach to monitor data changes in individual components is to use the useQuery or useQueryClient hooks. Below are detailed explanations and examples of both methods:

Using useQuery Hook

useQuery is a hook in React Query used to fetch data and subscribe to data changes. When data changes (e.g., backend data is updated), React Query automatically re-fetches the data and triggers re-rendering of the component.

Example:

Suppose we have an API endpoint for fetching user information, and we want to display it in the component, updating it whenever the data changes.

jsx
import { useQuery } from 'react-query'; function UserProfile({ userId }) { const { data, isLoading, error } = useQuery(['user', userId], () => fetch(`https://api.example.com/users/${userId}`).then(res => res.json() ) ); 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> ); }

In this example, whenever userId changes, the useQuery hook automatically re-fetches the data and triggers re-rendering of the component with the new data.

Using useQueryClient Hook

The useQueryClient hook can be used to manually manipulate cached query data, such as fetching, updating, and observing data.

Example:

If you want to not only fetch data but also perform actions when data updates, you can use useQueryClient to observe the state of specific queries.

jsx
import { useQueryClient } from 'react-query'; function MyComponent() { const queryClient = useQueryClient(); useEffect(() => { const unsubscribe = queryClient.getQueryCache().subscribe(query => { if (query.queryKey === 'user') { console.log('User query updated!', query.state.data); } }); return () => unsubscribe(); }, [queryClient]); // Component other logic... }

In this example, we subscribe to the query cache and log the updated data whenever the query key matches user. This allows us to monitor when data related to a specific user changes and respond accordingly.

Summary

In React Query, you can use the useQuery hook to automatically subscribe to and respond to data changes, or use the useQueryClient hook for more granular control and monitoring of data changes. Both methods effectively enable developers to observe and respond to data changes within components.

2024年8月5日 11:27 回复

你的答案