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

How to show loading button during mutation in react query

1个答案

1

In React Query, when executing mutations (such as adding, updating, or deleting data), you can effortlessly monitor and display loading states by using the useMutation hook. The useMutation hook returns an object containing multiple properties and methods, including tools for managing and accessing mutation states.

How to Display Loading States Using useMutation

  1. Setting Up the Mutation: First, define a mutation function that performs the actual data operations, such as API calls.

  2. Using the useMutation Hook: In your component, pass the above mutation function to useMutation to receive a mutation object that includes methods and states for controlling the mutation.

  3. Retrieving and Using the isLoading State: The object returned by useMutation contains an isLoading property, which is true during mutation execution and becomes false after completion. You can leverage this property to display a loading indicator in the UI.

Example Code

Assume we have an API function for adding a user; we can use useMutation to add a user and display loading states as follows:

jsx
import { useMutation } from 'react-query'; function addUser(userData) { return fetch('/api/users', { method: 'POST', body: JSON.stringify(userData), headers: { 'Content-Type': 'application/json', }, }).then(res => res.json()); } function CreateUserComponent() { const { mutate, isLoading } = useMutation(addUser); const handleAddUser = userData => { mutate(userData); }; return ( <div> <button onClick={() => handleAddUser({ name: 'John Doe' })}> Add User </button> {isLoading && <p>Loading...</p>} </div> ); }

In this example:

  • We define an addUser function that handles sending a POST request to the server.
  • In the component, we use useMutation and pass the addUser function.
  • We destructure to obtain mutate and isLoading.
  • When the button is clicked, handleAddUser is invoked, triggering the mutation via mutate.
  • Based on the value of isLoading, we display a loading message in the UI.

By implementing this approach, you can provide users with clear feedback during asynchronous operations, thereby enhancing the overall user experience.

2024年6月29日 12:07 回复

你的答案