2022-06-02 02:26:52 +00:00
|
|
|
import { AxiosInstance, AxiosRequestConfig, default as axios } from "axios";
|
2022-06-01 23:29:37 +00:00
|
|
|
import { useContext, useMemo } from "react";
|
2022-06-08 15:38:30 +00:00
|
|
|
import { LoginContext } from "../components/contexts/login";
|
2022-06-01 23:29:37 +00:00
|
|
|
import { FestaLoginData } from "../types/user";
|
|
|
|
|
2022-06-02 02:26:52 +00:00
|
|
|
export function useAxios<D>(config: AxiosRequestConfig<D> = {}, data?: FestaLoginData | null): AxiosInstance {
|
2022-06-01 23:29:37 +00:00
|
|
|
const loginContext = useContext(LoginContext)
|
|
|
|
|
|
|
|
let login = data || loginContext?.[0]
|
|
|
|
|
2022-06-02 02:26:52 +00:00
|
|
|
return useMemo(
|
|
|
|
() => {
|
|
|
|
const ax = axios.create({
|
|
|
|
...config,
|
|
|
|
headers: {
|
|
|
|
...(config.headers ?? {}),
|
|
|
|
Authorization: login ? `Bearer ${login.token}` : false,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
return ax
|
|
|
|
},
|
|
|
|
[config, login]
|
|
|
|
)
|
2022-06-01 23:29:37 +00:00
|
|
|
}
|