ChatGPT-Next-Web/app/store/usage.ts
ガオガオ 6ac26b7d4a feat:修复apikey使用额度接口缓存问题和修复setting页面针对该接口频繁调用的问题
1.为了解决缓存问题,更新了调用apikey使用额度接口的方法。由于nextjs的fetch默认会缓存同样参数的请求,需要针对fetch加入cache: 'no-store' 的参数修复以避免这一现象。(https://beta.nextjs.org/docs/data-fetching/fetching#dynamic-data-fetching)
2.为了提升用户体验,引入了usageStore,该存储库能够在有数据的情况下,优先使用缓存数据来加载apikey使用额度的信息。只有当重新检查的按钮被点击时,才会再次调用apikey使用额度接口更新usageStore数据,并且在页面上显示最新的更新数据。通过实现这种操作,我们能够避免在进入setting页面时频繁地调用apikey使用额度接口,从而进一步提升响应速度和用户体验。
2023-04-13 01:50:25 +08:00

42 lines
975 B
TypeScript

import { create } from "zustand";
import { persist } from "zustand/middleware";
export interface UsageStore {
used: string;
subscription: string;
updateUsage: (used?: string, subscription?: string) => void;
hasUsageData: () => boolean;
}
const USAGE_KEY = "api-usage";
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
export const useUsageStore = create<UsageStore>()(
persist(
(set, get) => ({
used: "",
subscription: "",
updateUsage(used?: string, subscription?: string) {
set((state) => ({
used: used ?? "[?]",
subscription: subscription ?? "[?]",
}));
},
hasUsageData() {
const used = get().used;
const sub = get().subscription;
const hasUsed = used != "" && used != "[?]";
const hasSubscription = sub != "" && sub != "[?]";
return hasUsed && hasSubscription;
},
}),
{
name: USAGE_KEY,
version: 1,
},
),
);