Home > Web Front-end > JS Tutorial > React Query Database Integration Guide: Quick Start Tutorial

React Query Database Integration Guide: Quick Start Tutorial

WBOY
Release: 2023-09-26 08:42:32
Original
850 people have browsed it

React Query 数据库集成指南:快速上手教程

React Query Database Integration Guide: Quick Start Tutorial

Introduction:
React Query is a powerful data query library that provides a simple and efficient way to manage and query application data. Its design concept is based on Hooks, making it very simple to use it in React applications. In this guide, we’ll focus on integrating React Query with a database to enable fast querying and updating of data.

1. Install and set up React Query
First, we need to install React Query. Open a terminal and run the following command in your project directory:

npm install react-query
Copy after login

After the installation is complete, we need to set up the provider for React Query in the root component of the application. In your root component, add the following code:

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

const queryClient = new QueryClient();

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

Now your React app has React Query integrated!

2. Create a database integration layer
Next, we will create a database integration layer to manage our data operations. We'll use a hypothetical database API for our example. In your project, create a file named api.js and add the following code:

export async function fetchUsers() {
  // 发送请求获取用户数据
}

export async function deleteUser(id) {
  // 发送请求删除指定 id 的用户
}

export async function updateUser(id, data) {
  // 发送请求更新指定 id 的用户数据
}

export async function createUser(data) {
  // 发送请求创建新用户
}
Copy after login

In this file, we define respectively getting users, deleting users, and updating Users and functions that create users. Depending on your actual situation, you may need to adjust the implementation details of these functions.

3. Use React Query for data query
Now we can start using React Query for data query. In your component, import the required Hooks and use them to query the data. The following is an example of querying a user list:

import { useQuery } from 'react-query';

import { fetchUsers } from './api';

function UserList() {
  const { data, isLoading, isError } = useQuery('users', fetchUsers);

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

  if (isError) {
    return <div>Error occurred while fetching data.</div>;
  }

  return (
    <div>
      {data.map((user) => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
}
Copy after login

In this example, we use useQuery Hook to query user data. The first parameter is a string that identifies the key value of the query. The second parameter is a function in which we call the fetchUsers function we defined earlier to get user data. useQuery Hook will return an object containing the query results from which we can get data, loading status and error status.

4. Use React Query for data update
In addition to querying data, React Query also provides Hooks for updating data. In your component, import the useMutation Hook and use it to update user data. The following is an example of updating a user:

import { useMutation } from 'react-query';

import { updateUser } from './api';

function UserForm({ user }) {
  const mutation = useMutation((data) => updateUser(user.id, data));

  const handleSubmit = (event) => {
    event.preventDefault();

    const formData = new FormData(event.target);
    const userData = Object.fromEntries(formData.entries());

    mutation.mutate(userData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" defaultValue={user.name} />
      <input type="text" name="email" defaultValue={user.email} />
      <button type="submit" disabled={mutation.isLoading}>
        {mutation.isLoading ? 'Saving...' : 'Save'}
      </button>
    </form>
  );
}
Copy after login

In this example, we use useMutation Hook to update user data. We pass the updateUser function to useMutation and it will return an object containing the mutate function. We call the mutation.mutate function when the form is submitted, passing the form data to it as a parameter, thereby triggering the update of the data.

Conclusion:
This guide introduces how to integrate React Query and database in React applications to achieve fast data query and update. By following the steps above, you can easily start leveraging React Query for data management. Hope this article helps you!

The above is the detailed content of React Query Database Integration Guide: Quick Start Tutorial. For more information, please follow other related articles on the PHP Chinese website!

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