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

How to handle multiple mutations in parallel with react-query

1个答案

1

In the React Query library, handling parallel mutations can simplify the management of backend data updates. React Query handles data mutations through the useMutation hook, and to execute multiple mutations in parallel, we can trigger multiple useMutation hooks simultaneously.

First, we need to install and import the React Query library:

bash
npm install react-query

Then, we can follow these steps to implement parallel mutations:

Step 1: Create Mutation Functions

Each mutation may correspond to different API calls. For example, assume we have two API functions: updateUser and deletePost, used for updating user information and deleting posts, respectively.

javascript
const updateUser = async (userData) => { const response = await fetch('/api/user/update', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; const deletePost = async (postId) => { const response = await fetch(`/api/posts/${postId}`, { method: 'DELETE', }); if (!response.ok) { throw new Error('Network response was not ok'); } return postId; };

Step 2: Use the useMutation Hook

In the component, we can use the useMutation hook to create a mutation handler for each API function.

javascript
import { useMutation, useQueryClient } from 'react-query'; const MyComponent = () => { const queryClient = useQueryClient(); const mutation1 = useMutation(updateUser, { onSuccess: () => { queryClient.invalidateQueries('userData'); } }); const mutation2 = useMutation(deletePost, { onSuccess: () => { queryClient.invalidateQueries('posts'); } }); // Function to execute mutations in parallel const handleMutations = async () => { try { const userUpdate = mutation1.mutateAsync({ userId: 1, name: 'Alice' }); const postDeletion = mutation2.mutateAsync(123); await Promise.all([userUpdate, postDeletion]); console.log('Both mutations completed successfully'); } catch (error) { console.error('Error in mutations', error); } }; return ( <div> <button onClick={handleMutations}>Update User and Delete Post</button> </div> ); };

In the above code, mutation1 and mutation2 handle user updates and post deletions, respectively. We use the mutateAsync method to include both mutations in handleMutations, and Promise.all ensures they execute in parallel. This approach not only simplifies mutation management but also effectively utilizes network resources to improve application performance.

Thus, we can effectively handle multiple mutation operations in parallel while maintaining code clarity and maintainability.

2024年8月5日 11:02 回复

你的答案