Cấp bậc tác giả:

TRAINING

Xử Lý API Calls Trong React Một Cách Tối Ưu Với React Query

Được viết bởi webmaster ngày 13/06/2024 lúc 01:43 PM
React Query là một thư viện mạnh mẽ giúp quản lý và đồng bộ hóa dữ liệu phía server trong các ứng dụng React. Nếu bạn đang phát triển một ứng dụng React và cần thường xuyên gọi API để lấy dữ liệu, React Query sẽ là công cụ hữu ích giúp bạn xử lý công việc này một cách tối ưu và dễ dàng hơn.
  • 0
  • 202

Xử Lý API Calls Trong React Một Cách Tối Ưu Với React Query

Xử lý các cuộc gọi API trong React bằng cách sử dụng React Query giúp quản lý dữ liệu máy chủ một cách tối ưu, giảm thiểu độ phức tạp và tăng hiệu suất của ứng dụng. React Query cung cấp các công cụ để thực hiện các truy vấn, quản lý bộ nhớ cache, và xử lý các trạng thái tải dữ liệu.

Dưới đây là các bước để tích hợp và sử dụng React Query trong một ứng dụng React:

Bước 1: Cài đặt React Query
Cài đặt React Query bằng npm:
npm install @tanstack/react-query

Bước 2: Cấu hình React Query
Tạo một file riêng cho cấu hình React Query, ví dụ src/queryClient.js:

import { QueryClient } from '@tanstack/react-query';
const queryClient = new QueryClient();
export default queryClient;

Bước 3: Thiết lập QueryClientProvider
Bọc ứng dụng của bạn với QueryClientProvider trong src/index.js hoặc src/App.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { QueryClientProvider } from '@tanstack/react-query';
import queryClient from './queryClient';
import App from './App';

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

Bước 4: Sử dụng React Query để gọi API
Dưới đây là một ví dụ về cách sử dụng useQuery để gọi API:

Tạo một hàm để fetch dữ liệu
Tạo một hàm để gọi API, ví dụ src/api.js:
export const fetchProducts = async () => {
  const response = await fetch('https://api.example.com/products');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

Sử dụng useQuery để gọi API trong một component
Trong một component, sử dụng useQuery để gọi API và xử lý các trạng thái khác nhau:

import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchProducts } from './api';

const Products = () => {
  const { data, error, isLoading, isError } = useQuery(['products'], fetchProducts);

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

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

  return (
    <div>
      <h1>Products</h1>
      <ul>
        {data.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default Products;

Bước 5: Tự động làm mới dữ liệu (Refetching)
React Query cung cấp nhiều tùy chọn để tự động làm mới dữ liệu khi cần. Ví dụ, bạn có thể tự động làm mới dữ liệu khi cửa sổ tập trung lại:

const { data, error, isLoading, isError } = useQuery(['products'], fetchProducts, {
  refetchOnWindowFocus: true,
});

Bước 6: Thêm dữ liệu (Mutations)
Để thêm hoặc cập nhật dữ liệu, bạn có thể sử dụng useMutation:

Tạo hàm thêm dữ liệu

export const addProduct = async (newProduct) => {
  const response = await fetch('https://api.example.com/products', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(newProduct),
  });
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

Sử dụng useMutation trong component

import React, { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { addProduct } from './api';

const AddProduct = () => {
  const [productName, setProductName] = useState('');
  const queryClient = useQueryClient();

  const mutation = useMutation(addProduct, {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries(['products']);
    },
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    mutation.mutate({ name: productName });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={productName}
        onChange={(e) => setProductName(e.target.value)}
        placeholder="Product Name"
      />
      <button type="submit">Add Product</button>
      {mutation.isLoading && <div>Adding product...</div>}
      {mutation.isError && <div>Error: {mutation.error.message}</div>}
    </form>
  );
};

export default AddProduct;

Với các bước trên, bạn đã tích hợp React Query vào ứng dụng React của mình và sử dụng nó để xử lý các cuộc gọi API một cách tối ưu. React Query giúp quản lý trạng thái tải dữ liệu, bộ nhớ cache, và tự động làm mới dữ liệu, giúp đơn giản hóa việc xử lý dữ liệu trong các ứng dụng React.

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML