axios

Axios là gì ? Cách sử dụng Axios trong 1 dự án React

Axios là một thư viện JavaScript dùng để gửi các yêu cầu HTTP từ trình duyệt hoặc Node.js. Giúp hỗ trợ các tính năng nổi bật như:

2. Cài đặt và thiết lập trong dự án react

Trước tiên, bạn cần cài đặt vào dự án của mình. Mở terminal và chạy lệnh sau:

				
					yarn add axios

				
			

Hoặc, nếu bạn dùng npm:

				
					npm install axios

				
			

3. Thiết lập Axios cơ bản

Tạo một file axiosConfig.js để cấu hình cơ bản cho Axios, giúp đơn giản hóa việc gọi API sau này. 

Ví dụ:

				
					// src/axiosConfig.js
import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com', // API mẫu
  headers: {
    'Content-Type': 'application/json',
  },
});

export default axiosInstance;

				
			

4. Sử dụng Axios trong react

Ví dụ về các phương thức HTTP cơ bản

Giả sử bạn đang có một component App.js, dưới đây là các ví dụ mã để sử dụng các phương thức HTTP.

				
					// src/App.js
import <a href="https://fstack.io.vn/blog/react-query-la-gi-tai-sao-nen-dung-react-query/">React</a>, { useEffect, <a href="https://fstack.io.vn/blog/react-hook-la-gi-6-hook-co-ban-trong-react/">useState</a> } from 'react';
import axiosInstance from './axiosConfig';

function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  // Hàm GET: Lấy danh sách dữ liệu
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await axiosInstance.get('/posts');
      setData(response.data);
    } catch (error) {
      console.error('Lỗi khi lấy dữ liệu:', error);
    }
    setLoading(false);
  };

  // Hàm POST: Thêm dữ liệu mới
  const createData = async () => {
    try {
      const newPost = { title: 'Axios trong React', body: 'Hướng dẫn cơ bản' };
      const response = await axiosInstance.post('/posts', newPost);
      setData([response.data, ...data]);
    } catch (error) {
      console.error('Lỗi khi tạo dữ liệu:', error);
    }
  };

  // Hàm PUT: Cập nhật dữ liệu
  const updateData = async (id) => {
    try {
      const updatedPost = { title: 'Đã cập nhật với Axios' };
      await axiosInstance.put(`/posts/${id}`, updatedPost);
      setData(data.map((post) => (post.id === id ? { ...post, ...updatedPost } : post)));
    } catch (error) {
      console.error('Lỗi khi cập nhật dữ liệu:', error);
    }
  };

  // Hàm DELETE: Xóa dữ liệu
  const deleteData = async (id) => {
    try {
      await axiosInstance.delete(`/posts/${id}`);
      setData(data.filter((post) => post.id !== id));
    } catch (error) {
      console.error('Lỗi khi xóa dữ liệu:', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      <h1><span class="ez-toc-section" id="Danh_sach_bai_viet"></span>Danh sách bài viết<span class="ez-toc-section-end"></span></h1>
      {loading && <p>Đang tải...</p>}
      <button onClick={createData}>Thêm bài viết</button>
      <ul>
        {data.map((post) => (
          <li key={post.id}>
            <h2><span class="ez-toc-section" id="posttitle"></span>{post.title}<span class="ez-toc-section-end"></span></h2>
            <p>{post.body}</p>
            <button onClick={() => updateData(post.id)}>Cập nhật</button>
            <button onClick={() => deleteData(post.id)}>Xóa</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

				
			

5.Interceptors trong Axios

Bạn có thể dùng Interceptors để thêm token vào header trước khi gửi yêu cầu:

				
					// src/axiosConfig.js
axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

				
			

thiết lập Interceptor cho response :

				
					
// Interceptor cho response
axiosInstance.interceptors.response.use(
  (response) => {
    // Xử lý response trước khi trả về cho component
    // Ví dụ: chỉ lấy phần dữ liệu cần thiết
    return response.data;
  },
  (error) => {
    // Xử lý lỗi toàn cục
    if (error.response) {
      // Xử lý lỗi từ server, ví dụ lỗi xác thực
      if (error.response.status === 401) {
        console.error('Bạn không có quyền truy cập. Vui lòng đăng nhập lại.');
      } else if (error.response.status === 404) {
        console.error('Dữ liệu không tìm thấy.');
      }
    } else if (error.request) {
      console.error('Không có phản hồi từ server.');
    } else {
      console.error('Lỗi khi thiết lập yêu cầu:', error.message);
    }
    return Promise.reject(error);
  }
);
				
			

6.Tối ưu hóa nhiều yêu cầu với axios.all()

Sử dụng axios.all() để gửi nhiều yêu cầu đồng thời, giúp tối ưu hóa tốc độ tải dữ liệu:

				
					const fetchDataConcurrently = async () => {
  try {
    const [posts, comments] = await axios.all([
      axiosInstance.get('/posts'),
      axiosInstance.get('/comments'),
    ]);
    console.log('Bài viết:', posts.data);
    console.log('Bình luận:', comments.data);
  } catch (error) {
    handleError(error);
  }
};

				
			

7.Kết luận

Với những ví dụ trên, bạn đã có thể nắm được cách dùng Axios trong React để thực hiện các thao tác HTTP phổ biến như GET, POST, PUT, DELETE. Tận dụng các tính năng mạnh mẽ của Axios sẽ giúp ứng dụng của bạn dễ dàng quản lý dữ liệu và xử lý lỗi.

Ở trên là 1 số chia sẻ về axios của mình, vì đây đa phần là kiến thức mình tự học nên có thể bài viết này có thể có nhiều chỗ chưa chính xác và thiếu sót, mong mọi người góp ý ở dưới phần bình luận để bài viết thêm hoàn chỉnh và xây dựng một cộng đồng nơi mọi người có thể chia sẻ kinh nghiệm lập trình cho nhau 😘.

Bài viết liên quan

Building a High-Converting Shopify Product Page: Design, Copy, and Psychology

Your Shopify product page is the digital storefront where potential customers decide whether to make a purchase. It’s…

ByByAuto Mation Dec 30, 2025

The Impact of Page Speed on Conversions: Optimizing Your Shopify Store for a Faster User Experience

In the fast-paced world of e-commerce, every second counts. A slow-loading Shopify store can be the difference between…

ByByAuto Mation Dec 29, 2025

Shopify Order Routing: How to Ship From Multiple Warehouses Efficiently

In today’s competitive e-commerce landscape, efficient order fulfillment is crucial for customer satisfaction and business success. For Shopify…

ByByAuto Mation Dec 29, 2025

Shopify SEO Beyond Keywords: Optimizing for Voice Search and Visual Discovery

In the ever-evolving landscape of e-commerce, staying ahead of the curve is paramount for Shopify store owners. While…

ByByAuto Mation Dec 29, 2025

Subscribe
Thông báo của
guest

0 Comments
Cũ nhất
Mới nhất Được bình chọn nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận

0
Rất mong nhận được suy nghĩ của bạn, vui lòng bình luận.x
()
x