/home/vianto5/realtylifestyleproperties.mx/wp-content/plugins/code-snippets/js/hooks
Edit: /home/vianto5/realtylifestyleproperties.mx/wp-content/plugins/code-snippets/js/hooks/useAxios.ts (1368B)
import { useMemo } from 'react'
import axios from 'axios'
import type { AxiosInstance, AxiosResponse, CreateAxiosDefaults } from 'axios'
export interface AxiosAPI {
get:
(url: string) => Promise>
post: (url: string, data?: D) => Promise>
del: (url: string) => Promise>
axiosInstance: AxiosInstance
}
const debugRequest = async (
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
url: string,
doRequest: Promise>,
data?: D
): Promise> => {
console.debug(`${method} ${url}`, ...data ? [data] : [])
const response = await doRequest
console.debug('Response', response)
return response
}
export const useAxios = (defaultConfig: CreateAxiosDefaults): AxiosAPI => {
const axiosInstance = useMemo(() => axios.create(defaultConfig), [defaultConfig])
return useMemo((): AxiosAPI => ({
get: (url: string): Promise> =>
debugRequest('GET', url, axiosInstance.get, never>(url)),
post: (url: string, data?: D) =>
debugRequest('POST', url, axiosInstance.post, D>(url, data), data),
del: (url: string) =>
debugRequest('DELETE', url, axiosInstance.delete, never>(url)),
axiosInstance
}), [axiosInstance])
}