diff --git a/app/components/collabora/hooks.ts b/app/components/collabora/hooks.ts index aedae0d..f398719 100644 --- a/app/components/collabora/hooks.ts +++ b/app/components/collabora/hooks.ts @@ -9,7 +9,6 @@ * @encoding UTF-8 */ -import { useFetcher } from '@remix-run/react'; import { RefObject, useCallback, useEffect, useMemo, useState } from 'react'; import { COLLABORA_URL } from '~/config/api-config'; import { toastService } from '../ui/Toast'; @@ -35,37 +34,71 @@ export function useCollaboraConfig( userId: string, userName: string ) { - const fetcher = useFetcher(); + const [config, setConfig] = useState(null); + const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { - if (fetcher.state === 'idle' && !fetcher.data) { - // 构建查询参数 - const params = new URLSearchParams({ - fileId, - mode, - userId, - userName, - }); - - // 加载配置 - fetcher.load(`/api/collabora/config?${params}`); + if (!fileId) { + setConfig(null); + setError('文件路径不能为空'); + setLoading(false); + return; } - }, [fileId, mode, userId, userName, fetcher]); - // 检查错误 - useEffect(() => { - if (fetcher.data && 'error' in fetcher.data) { - const errorData = fetcher.data as { error: string }; - const errorMessage = errorData.error || '加载配置失败'; - setError(errorMessage); - toastService.error(`加载文档配置失败: ${errorMessage}`); + const controller = new AbortController(); + const params = new URLSearchParams({ + fileId, + mode, + userId, + userName, + }); + + async function loadConfig() { + setLoading(true); + setError(null); + setConfig(null); + + try { + const response = await fetch(`/api/collabora/config?${params}`, { + method: 'GET', + signal: controller.signal, + headers: { + Accept: 'application/json', + }, + }); + + const result = (await response.json()) as CollaboraConfig | { error?: string }; + + if (!response.ok || ('error' in result && result.error)) { + const errorMessage = + ('error' in result && result.error) || `加载配置失败 (${response.status})`; + setError(errorMessage); + toastService.error(`加载文档配置失败: ${errorMessage}`); + return; + } + + setConfig(result as CollaboraConfig); + } catch (err) { + if (controller.signal.aborted) return; + const errorMessage = err instanceof Error ? err.message : '加载配置失败'; + setError(errorMessage); + toastService.error(`加载文档配置失败: ${errorMessage}`); + } finally { + if (!controller.signal.aborted) { + setLoading(false); + } + } } - }, [fetcher.data]); + + void loadConfig(); + + return () => controller.abort(); + }, [fileId, mode, userId, userName]); return { - config: fetcher.data && !('error' in fetcher.data) ? fetcher.data : null, - loading: fetcher.state === 'loading', + config, + loading, error, }; }