updated react-openapi
This commit is contained in:
45
react-openapi/src/hooks/useApi.ts
Normal file
45
react-openapi/src/hooks/useApi.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
|
||||
let apiClient: AxiosInstance | null = null;
|
||||
|
||||
export function initApi(baseUrl: string, getToken?: () => string | null): AxiosInstance {
|
||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
apiClient = axios.create({
|
||||
baseURL: baseUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
const token = getToken?.();
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(res) => res,
|
||||
(error) => {
|
||||
if (error.response?.status === 401 && getToken) {
|
||||
const currentToken = getToken();
|
||||
if (currentToken) {
|
||||
const tokenStore = { clear: () => localStorage.removeItem("token") };
|
||||
tokenStore.clear();
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
export function getApi(): AxiosInstance {
|
||||
if (!apiClient) {
|
||||
throw new Error("API client not initialized. Make sure AppProvider is mounted.");
|
||||
}
|
||||
return apiClient;
|
||||
}
|
||||
Reference in New Issue
Block a user