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

How to share data across multiple components with react-query useMutation

1个答案

1

In React, useMutation is a hook from the react-query library used for handling asynchronous update operations, such as data submission. To share data across multiple components, we typically combine the use of QueryClient and QueryClientProvider from react-query.

Here is a detailed explanation of the steps and examples:

Step 1: Install react-query

First, ensure that react-query is installed in your project.

bash
npm install react-query

Step 2: Set up QueryClient and QueryClientProvider

In your application's top-level component, set up QueryClient and QueryClientProvider. This enables access to the same query client and cache in any component of the application.

jsx
// src/App.js 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;

Step 3: Using useMutation in Components

Assume we have an API for updating user data. We can use the useMutation hook in multiple components to call this API and share state through react-query's caching mechanism.

jsx
// src/updateUser.js export const updateUser = async (userData) => { const response = await fetch('/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }); return response.json(); };
jsx
// src/ComponentA.js import { useMutation } from 'react-query'; import { updateUser } from './updateUser'; function ComponentA() { const mutation = useMutation(userData => updateUser(userData), { onSuccess: () => { // Handle success console.log('User updated successfully'); }, }); return ( <div> <button onClick={() => mutation.mutate({ id: 1, name: 'John Doe' })}> Update User </button> </div> ); } export default ComponentA;

Step 4: Handling State Updates

Other components can now use the onSuccess and onError callbacks from useQuery or useMutation to respond to these updates, or automatically fetch updates by observing data changes.

Additionally, by using methods of QueryClient, such as queryClient.invalidateQueries or queryClient.setQueryData, you can trigger updates in another component from within one component.

Conclusion

By following these steps, you can share and synchronize the useMutation state across multiple components using react-query. This not only makes state management clearer and more concise but also leverages the powerful data synchronization and caching features provided by react-query.

2024年8月5日 11:19 回复

你的答案