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

How to refetch queries from sibling component with react-query

1个答案

1

React Query is a powerful library for managing server state in React applications, providing features such as data fetching, caching, synchronization, and updates. To refetch data from a peer component, leverage the useQueryClient hook provided by React Query. Below are detailed steps and example code:

Steps

  1. Ensure React Query is properly set up in your project. Verify your application is wrapped with QueryClientProvider and passes a QueryClient instance.

  2. Use the useQuery hook in the source component. Here, the "source component" refers to the component responsible for data fetching.

  3. Use the useQueryClient hook in the target component to access the queryClient instance. This hook grants access to the queryClient instance, enabling interaction with the React Query cache and utilities.

  4. Call the queryClient.invalidateQueries method in the target component. This method invalidates one or more queries, triggering a refetch. Specify a particular query key to invalidate only those queries.

Example Code

Assume we have two components, ComponentA and ComponentB. ComponentA fetches user data, while ComponentB triggers a refetch of this data.

jsx
// App.js import React from 'react'; import { QueryClient, QueryClientProvider } from 'react-query'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <ComponentA /> <ComponentB /> </QueryClientProvider> ); } export default App;
jsx
// ComponentA.js import React from 'react'; import { useQuery } from 'react-query'; async function fetchUserData() { const response = await fetch('https://api.example.com/users'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); } function ComponentA() { const { data, error, isLoading } = useQuery('users', fetchUserData); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> {data.map(user => ( <p key={user.id}>{user.name}</p> ))} </div> ); } export default ComponentA;
jsx
// ComponentB.js import React from 'react'; import { useQueryClient } from 'react-query'; function ComponentB() { const queryClient = useQueryClient(); const refetchUsers = () => { queryClient.invalidateQueries('users'); }; return ( <button onClick={refetchUsers}>Refetch Users</button> ); } export default ComponentB;

Summary

In this example, ComponentA uses useQuery to fetch user data. ComponentB includes a button that, when clicked, triggers a refetch by calling queryClient.invalidateQueries('users'). This approach promotes component decoupling, as they interact through query keys (e.g., 'users') rather than direct references or state lifting. This enhances maintainability and scalability of the code.

2024年8月5日 11:20 回复

你的答案