ts + axios + useRequest (ahooks) - implement request encapsulation

Now more and more projects are starting to be ts, let's learn together today about the request encapsulation of ts.

First two dependencies need to be installed:

npm i axios -S

npm i ahooks -S

Introduce:

import { useRequest } from 'ahooks';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

Define a generic interface for specifying the type of request parameters and response data

interface RequestParams<T> {
  url: string;
  method: string;
  data?: T;
}

// 定义一个范型函数,用于发送 GET 请求
function get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return axios.get<T>(url, config);
}

// 定义一个范型函数,用于发送 POST 请求
function post<T>(params: RequestParams<T>, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  return axios.post<T>(params.url, params.data, config);
}

useRequest using ahooks:

 // 使用 useRequest hooks 发送 GET 请求
  const { data, loading, error } = useRequest<{ name: string }>('https://api.example.com/data', {
    requestMethod: () => get('https://api.example.com/data'),
  });

Use get and post directly:

// 调用 GET 方法
get<{ name: string }>('https://api.example.com/data')
  .then(response => {
    console.log(response.data.name);
  })
  .catch(error => {
    console.error(error);
  });

// 调用 POST 方法
const postData = { name: 'John' };
const postParams = { url: 'https://api.example.com/data', method: 'post', data: postData };
post<{ status: string }>(postParams)
  .then(response => {
    console.log(response.data.status);
  })
  .catch(error => {
    console.error(error);
  });

Guess you like

Origin blog.csdn.net/congxue666/article/details/132163261