PluginProbe
Code Snippets / 4.0.0-beta.1
Code Snippets v4.0.0-beta.1
4.0.0-beta.2 3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 All 65 releases
code-snippets / js / hooks / useAxios.ts

useAxios.ts in Code Snippets 4.0.0-beta.1, at js/hooks/useAxios.ts

40 lines 1.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { useMemo } from 'react'
2 import axios from 'axios'
3 import type { AxiosInstance, AxiosResponse, CreateAxiosDefaults } from 'axios'
4
5 export interface AxiosAPI {
6 get: <T>(url: string) => Promise<AxiosResponse<T, never>>
7 post: <T, D>(url: string, data?: D) => Promise<AxiosResponse<T, D>>
8 del: <T>(url: string) => Promise<AxiosResponse<T, never>>
9 axiosInstance: AxiosInstance
10 }
11
12 const debugRequest = async <T, D = never>(
13 method: 'GET' | 'POST' | 'PUT' | 'DELETE',
14 url: string,
15 doRequest: Promise<AxiosResponse<T, D>>,
16 data?: D
17 ): Promise<AxiosResponse<T, D>> => {
18 console.debug(`${method} ${url}`, ...data ? [data] : [])
19 const response = await doRequest
20 console.debug('Response', response)
21 return response
22 }
23
24 export const useAxios = (defaultConfig: CreateAxiosDefaults): AxiosAPI => {
25 const axiosInstance = useMemo(() => axios.create(defaultConfig), [defaultConfig])
26
27 return useMemo((): AxiosAPI => ({
28 get: <T>(url: string): Promise<AxiosResponse<T, never>> =>
29 debugRequest('GET', url, axiosInstance.get<T, AxiosResponse<T, never>, never>(url)),
30
31 post: <T, D>(url: string, data?: D) =>
32 debugRequest('POST', url, axiosInstance.post<T, AxiosResponse<T, D>, D>(url, data), data),
33
34 del: <T>(url: string) =>
35 debugRequest('DELETE', url, axiosInstance.delete<T, AxiosResponse<T, never>, never>(url)),
36
37 axiosInstance
38 }), [axiosInstance])
39 }
40