Loading...

Làm thế nào để viết axios một cách tiện ích với reactjs

Nếu làm việc với tư cách là 1 front-end developer thì sự tương tác giữa client với server để lấy data và xử lý là chuyện không còn xa lạ với các bạn. Và một thư viện mạnh mẽ và phổ biến để làm điều này là

Axios Axios npm packages

1. Cách sử dụng

Đầu tiên bạn sẽ tạo ra một instance của axios

import axios from "axios";
export const instance = axios.create({
    headers: {
        'content-type': 'application/json; charset=UTF-8'
    },
    timeout: 300000,
    timeoutErrorMessage: `Connection is timeout exceeded`
});

Tiếp theo sẽ dùng instance này để gọi request

instance.get('link request....')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Tới đây bạn có thể đặt câu hỏi

  • Nếu như có nhiều tương tác giữa client và server thì bạn sẽ phải viết đi viết lại điều này nhiều lần, trong code thì đây bạn đã vi phạm một lỗi được gọi là DRY (Don’t Repeat Yourself)

  • Và với vấn đề code lặp đi lặp lại như vậy, khi có 1 sự thay đổi code thì bạn sẽ phải tìm và sữ lại từng hàm trên

Nếu bạn có đặt câu hỏi như vậy thì phần tiếp theo sẽ dành cho bạn.

2. Viết axios để tái sử dụng

Đầu tiên bạn sẽ tạo 1 thư mục ví dụ src/api/core.ts và cũng như phần 1 bạn sẽ tạo instance của axios

import axios from "axios";
export const instance = axios.create({
    headers: {
        'content-type': 'application/json; charset=UTF-8'
    },
    timeout: 300000,
    timeoutErrorMessage: `Connection is timeout exceeded`
});

Theo đó bạn sẽ tạo 1 model để truyền params vào các hàm của axios mà mình sẽ hướng dẫn sắp tới

  • isLoading - show loading khi call request

  • payload, headers - để truyền xuống khi call request (như Authorization...)

  • url - đường dẫn tương tác với server

   export interface IRequest<T = any> {
    isLoading: boolean;
    payload: T;
    headers: {
        [key: string]: string | number;
    };
    url: string;
}

Ok!! Và bây giờ hãy viết những hàm tương tác với server bằng axios nào

import {AxiosResponse} from "axios";
export interface PromiseState<T = unknown> extends AxiosResponse<T> {
    totalItem: number;
}

export const BaseService = {
    get<T = any>({
                     url,
                     isLoading,
                     payload,
                     headers
                 }: Partial<IRequest>): Promise<PromiseState<T>> {
        if (isLoading)
           // todo show loading
        return instance.get<T, PromiseState<T>>(url, {
            params: payload,
            baseURL: 'link base url',
            headers: headers || {}
        })
    }
}

Và với các hàn put post delete bạn cũng có thể tham khảo và làm tương tự như vây

3. Sử dụng

Mình sẽ tạo 1 model về response
export interface ProductDetail{
  id: number;
  "title": string;
  "description": string;
  "price": number;
  "discountPercentage": number;
  "rating":number;
  "stock": number;
  "brand": string;
  "category": string;
  "thumbnail": string;
  "images": string[];
}

Bây giờ áp dụng những gì đã viết từ phần 2 dùng để gọi một request chi tiết sản phẩm

import {useEffect} from "react";
const getDetailProduct=async ()=>{
   const response= await BaseService.get<ProductDetail>({
        url:'https://dummyjson.com/products/1',
        isLoading:true
   })
    // reponse.data sẽ có kiểu là ProductDetail
    console.log('data',response.data);
}
useEffect(()=>{
    (async ()=>{
        await getDetailProduct();
    })()
},[])

4. Lời kết

Trong bài viết này mình chỉ hướng dẫn về cách viết tương tác giữa client và server, trong các phần tới mình sẽ ra thêm về cache, xử lý lỗi, mapper dữ liệu từ reponse với axios.


© 2024 Nguyen Ba Tran Van. All Rights Reserved.