From 49c81f620133ee2d1e3e2448ee6556590d07d70e Mon Sep 17 00:00:00 2001 From: TianHua Liu <61778232+Taoister39@users.noreply.github.com> Date: Mon, 7 Apr 2025 16:50:53 +0800 Subject: [PATCH] fix: the first function call creates multiple axios instances (#3273) --- src/services/api.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/services/api.ts b/src/services/api.ts index 90e1ac21..d2abad0f 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -3,13 +3,9 @@ import { getClashInfo } from "./cmds"; import { invoke } from "@tauri-apps/api/core"; import { useLockFn } from "ahooks"; -let axiosIns: AxiosInstance = null!; - -/// initialize some information -/// enable force update axiosIns -export const getAxios = async (force: boolean = false) => { - if (axiosIns && !force) return axiosIns; +let instancePromise: Promise = null!; +async function getInstancePromise() { let server = ""; let secret = ""; @@ -26,13 +22,22 @@ export const getAxios = async (force: boolean = false) => { if (info?.secret) secret = info?.secret; } catch {} - axiosIns = axios.create({ + const axiosIns = axios.create({ baseURL: `http://${server}`, headers: secret ? { Authorization: `Bearer ${secret}` } : {}, timeout: 15000, }); axiosIns.interceptors.response.use((r) => r.data); return axiosIns; +} + +/// initialize some information +/// enable force update axiosIns +export const getAxios = async (force: boolean = false) => { + if (!instancePromise || force) { + instancePromise = getInstancePromise(); + } + return instancePromise; }; /// Get Version