From 0cff882a3f77174237c21b98ac3427f6d1e65a0c Mon Sep 17 00:00:00 2001 From: Jason Date: Fri, 17 Oct 2025 19:18:10 +0800 Subject: [PATCH] refactor: improve code quality and consistency Changes: 1. Remove unused variable in useSettings.ts (readPersistedLanguage) 2. Replace manual state management with React Query in UsageFooter - Create useUsageQuery hook with 5-minute cache - Simplify component from 227 lines to 81 lines (-64%) - Improve consistency with project's React Query pattern - Enable automatic refetch and error handling --- src/components/UsageFooter.tsx | 57 +++++++--------------------------- src/hooks/useSettings.ts | 1 - src/lib/query/queries.ts | 18 +++++++++-- 3 files changed, 27 insertions(+), 49 deletions(-) diff --git a/src/components/UsageFooter.tsx b/src/components/UsageFooter.tsx index 5c057f3..2422100 100644 --- a/src/components/UsageFooter.tsx +++ b/src/components/UsageFooter.tsx @@ -1,7 +1,8 @@ -import React, { useEffect, useState, useRef } from "react"; +import React from "react"; import { RefreshCw, AlertCircle } from "lucide-react"; -import { usageApi, type AppType } from "@/lib/api"; -import { UsageResult, UsageData } from "../types"; +import { type AppType } from "@/lib/api"; +import { useUsageQuery } from "@/lib/query/queries"; +import { UsageData } from "../types"; interface UsageFooterProps { providerId: string; @@ -14,47 +15,11 @@ const UsageFooter: React.FC = ({ appType, usageEnabled, }) => { - const [usage, setUsage] = useState(null); - const [loading, setLoading] = useState(false); - - // 记录上次请求的关键参数,防止重复请求 - const lastFetchParamsRef = useRef(""); - - const fetchUsage = async () => { - // 防止并发请求 - if (loading) return; - - setLoading(true); - try { - const result = await usageApi.query(providerId, appType); - setUsage(result); - } catch (error: any) { - console.error("查询用量失败:", error); - setUsage({ - success: false, - error: error?.message || "查询失败", - }); - } finally { - setLoading(false); - } - }; - - useEffect(() => { - if (usageEnabled) { - // 生成当前参数的唯一标识(包含 usageEnabled 状态) - const currentParams = `${providerId}-${appType}-${usageEnabled}`; - - // 只有参数真正变化时才发起请求 - if (currentParams !== lastFetchParamsRef.current) { - lastFetchParamsRef.current = currentParams; - fetchUsage(); - } - } else { - // 如果禁用了,清空记录和数据 - lastFetchParamsRef.current = ""; - setUsage(null); - } - }, [providerId, usageEnabled, appType]); + const { data: usage, isLoading: loading, refetch } = useUsageQuery( + providerId, + appType, + usageEnabled, + ); // 只在启用用量查询且有数据时显示 if (!usageEnabled || !usage) return null; @@ -71,7 +36,7 @@ const UsageFooter: React.FC = ({ {/* 刷新按钮 */}