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

React query - how to subscribe to a mutation state change

1个答案

1

In React Query, mutation is a mechanism for executing asynchronous logic that may affect server data. For scenarios where you need to subscribe to mutation state changes, React Query provides several hooks for handling state and events.

Using the useMutation Hook

The useMutation hook is the primary tool in React Query for handling mutations. It not only allows you to execute an asynchronous function but also enables you to subscribe to various state changes of the mutation. These states include:

  • isLoading: set to true when the asynchronous operation is in progress
  • isSuccess: set to true when the asynchronous operation completes successfully
  • isError: set to true when the asynchronous operation throws an error
  • data: contains the data from the successful response of the asynchronous operation
  • error: contains the error information when the asynchronous operation fails

Implementation Example

Suppose we have an API addUser for adding a new user. Here's how to use the useMutation hook to execute this API and subscribe to different responses based on its state changes:

jsx
import React from 'react'; import { useMutation } from 'react-query'; function CreateUserComponent() { const { mutate, isLoading, isSuccess, isError, error } = useMutation(addUser, { // Add callbacks like `onSuccess`, `onError`, and `onSettled` here to handle specific events onSuccess: () => { console.log('User added successfully'); // Perform additional actions, such as updating the state or displaying notifications }, onError: (error) => { console.error('Error adding user:', error); // Handle errors, display error messages, etc. } }); const handleAddUser = () => { const userData = { name: 'John', email: 'john@example.com' }; mutate(userData); }; return ( <div> <button onClick={handleAddUser} disabled={isLoading}> Add User </button> {isLoading && <p>Adding user...</p>} {isSuccess && <p>User added!</p>} {isError && <p>Error: {error.message}</p>} </div> ); }

Explanation

  • mutate function: Used to trigger the mutation. It receives the data to pass to the asynchronous function.
  • State flags: Flags like isLoading, isSuccess, etc., allow you to update the UI based on the mutation's different states.
  • Event callbacks: Callbacks like onSuccess, onError, and onSettled allow you to execute additional logic when the mutation reaches specific states.

In this way, React Query provides a powerful and flexible approach to handling asynchronous data updates and rendering UI based on these state changes.

2024年6月29日 12:07 回复

你的答案