Home > Web Front-end > JS Tutorial > body text

How to add, delete, modify, and query data in React Query?

PHPz
Release: 2023-09-27 09:31:44
Original
1027 people have browsed it

如何在 React Query 中实现数据的增、删、改、查?

How to add, delete, modify and query data in React Query?

In modern web development, the architecture of front-end and back-end separation has been widely used. As front-end developers, we usually need to interact with the back-end data, including adding (Create), deleting (Delete), updating (Update) and querying (Query) data. In order to simplify these operations and improve development efficiency, the React Query library has become a popular choice. This article will introduce how to use React Query to add, delete, modify, and query data.

React Query is a state management library that focuses on managing asynchronous data. It provides a powerful set of tools and APIs for retrieving, updating, and deleting data, as well as automatically managing caching and invalidation of data.

First, we need to install and configure React Query. You can install React Query using the following command:

npm install react-query
Copy after login

or

yarn add react-query
Copy after login

Then, add the React Query Provider in the root component of your application:

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* 应用程序的其他组件 */}
    </QueryClientProvider>
  );
}
Copy after login

Next, Let's take a look at how to implement data addition, deletion, modification and query in React Query.

Create/Add new data

To create new data, we can use useMutation hook. This hook receives a function as a parameter and is used to send the request and create new data. This function must return a Promise and resolve after the data is successfully created.

import { useMutation } from 'react-query';

function CreateData() {
  const { mutate, isLoading } = useMutation((data) =>
    fetch('/api/data', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json())
  );

  const handleCreate = () => {
    mutate({ name: 'New Data' }); // 传递新数据到 mutate 函数
  };

  return (
    <div>
      <button onClick={handleCreate} disabled={isLoading}>
        {isLoading ? 'Creating...' : 'Create Data'}
      </button>
    </div>
  );
}
Copy after login

In the above code, we use the useMutation hook to create a component named CreateData. mutate The function is used to trigger requests and create new data. In this example, we send a POST request to the /api/data address with the new data as the body of the request. After the request is successful, the response is parsed by calling the res.json() method, and the data is returned after Promise resolves.

Delete data

To delete data, we can use the useMutation hook again and send a DELETE request. Similar to the create data example, we need to pass a delete function and resolve after the function returns a success result.

import { useMutation } from 'react-query';

function DeleteData({ dataId }) {
  const { mutate, isLoading } = useMutation(() =>
    fetch(`/api/data/${dataId}`, {
      method: 'DELETE',
    }).then((res) => res.json())
  );

  const handleDelete = () => {
    mutate();
  };

  return (
    <div>
      <button onClick={handleDelete} disabled={isLoading}>
        {isLoading ? 'Deleting...' : 'Delete Data'}
      </button>
    </div>
  );
}
Copy after login

In the above code, we define a component named DeleteData and create a delete function using the useMutation hook. This function sends a DELETE request to the address /api/data/{dataId}, where {dataId} is the unique identifier of the data to be deleted. After the request succeeds, we return the result as a Promise resolve.

Update data

To update data, we can use the useMutation hook again to send a PUT or PATCH request. Similar to the examples of creating and deleting data, we need to pass a function to update the data and resolve after the function returns success.

import { useMutation } from 'react-query';

function UpdateData({ dataId }) {
  const { mutate, isLoading } = useMutation((data) =>
    fetch(`/api/data/${dataId}`, {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json())
  );

  const handleUpdate = () => {
    mutate({ name: 'Updated Data' });
  };

  return (
    <div>
      <button onClick={handleUpdate} disabled={isLoading}>
        {isLoading ? 'Updating...' : 'Update Data'}
      </button>
    </div>
  );
}
Copy after login

In the above code, we created a component named UpdateData and created an update function using the useMutation hook. This function sends a PUT request to the /api/data/{dataId} address with the updated data as the body of the request. After the request succeeds, we return the result as a Promise resolve.

Query data

To query data, we can use useQuery hook in React Query. This hook receives a function as argument and returns an object containing the data. Within the function, we send a GET request and parse the data in the response.

import { useQuery } from 'react-query';

function GetData({ dataId }) {
  const { isLoading, error, data } = useQuery('data', () =>
    fetch(`/api/data/${dataId}`).then((res) => res.json())
  );

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h2>Data: {data.name}</h2>
    </div>
  );
}
Copy after login

In the above code, we used the useQuery hook to create a component named GetData. useQuery The hook receives a string as an identifier and automatically caches the data after a successful request. We send a GET request to the /api/data/{dataId} address and parse the data in the response. During data loading, we display a "Loading..." text. If an error occurs, we display the error text. Otherwise, we display the queried data.

In summary, we have learned how to use React Query to add, delete, modify, and query data. React Query provides many powerful tools and APIs to simplify data management and interaction. By using these tools and APIs, we can more easily manipulate data and improve the efficiency of front-end development. Hope this article can be helpful to you!

The above is the detailed content of How to add, delete, modify, and query data in React Query?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template