Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

opti: Use useSWR to cache request

Rene Wang61119dee740d
diff --git a/src/features/PageEditor/Header/index.tsx b/src/features/PageEditor/Header/index.tsx
index d78963d0abf..dcba645edcc 100644
--- a/src/features/PageEditor/Header/index.tsx
+++ b/src/features/PageEditor/Header/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { ActionIcon, Avatar, Dropdown, Text } from '@lobehub/ui';
+import { ActionIcon, Avatar, Dropdown, Skeleton, Text } from '@lobehub/ui';
import { ArrowLeftIcon, BotMessageSquareIcon, MoreHorizontal } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,10 +16,9 @@ import { useMenu } from './useMenu';
const Header = memo(() => {
const { t } = useTranslation('file');
- const currentEmoji = usePageEditorStore((s) => s.currentEmoji);
- const currentTitle = usePageEditorStore((s) => s.currentTitle);
- const parentId = usePageEditorStore((s) => s.parentId);
- const onBack = usePageEditorStore((s) => s.onBack);
+ const [currentEmoji, currentTitle, isLoadingContent, parentId, onBack] = usePageEditorStore(
+ (s) => [s.currentEmoji, s.currentTitle, s.isLoadingContent, s.parentId, s.onBack],
+ );
const { menuItems } = useMenu();
return (
@@ -35,9 +34,16 @@ const Header = memo(() => {
{/* Icon */}
{currentEmoji && <Avatar avatar={currentEmoji} shape={'square'} size={28} />}
{/* Title */}
- <Text ellipsis style={{ marginLeft: 4 }} weight={500}>
- {currentTitle || t('pageEditor.titlePlaceholder')}
- </Text>
+ {isLoadingContent ? (
+ <Skeleton.Button
+ active
+ style={{ height: 20, marginLeft: 4, maxWidth: 200, width: 200 }}
+ />
+ ) : (
+ <Text ellipsis style={{ marginLeft: 4 }} weight={500}>
+ {currentTitle || t('pageEditor.titlePlaceholder')}
+ </Text>
+ )}
</>
)}
{/* Auto Save Status */}
diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsx
index 176d1f651c0..12760bb6631 100644
--- a/src/features/PageEditor/StoreUpdater.tsx
+++ b/src/features/PageEditor/StoreUpdater.tsx
@@ -15,6 +15,21 @@ const log = debug('page:store-updater');
export type StoreUpdaterProps = Partial<PublicState>;
+// State machine types
+type InitPhase =
+ | 'idle' // Initial state
+ | 'waiting-for-data' // Waiting for SWR to fetch/return cached data
+ | 'initializing' // Setting metadata (currentDocId, title, emoji)
+ | 'loading-content' // Loading content into editor
+ | 'ready' // Initialization complete
+ | 'error'; // Error occurred
+
+interface InitState {
+ error?: Error;
+ phase: InitPhase;
+ targetPageId: string | undefined;
+}
+
const StoreUpdater = memo<StoreUpdaterProps>(
({ pageId, knowledgeBaseId, onDocumentIdChange, onSave, onDelete, onBack, parentId }) => {
const storeApi = useStoreApi();
@@ -24,13 +39,27 @@ const StoreUpdater = memo<StoreUpdaterProps>(
const editorState = useEditorState(editor);
const currentDocId = usePageEditorStore((s) => s.currentDocId);
- const fetchDocumentDetail = useFileStore((s) => s.fetchDocumentDetail);
+ // Use SWR hook for document fetching with caching
+ const { isLoading: isLoadingDetail, error: swrError } = useFileStore((s) =>
+ s.useFetchDocumentDetail(pageId),
+ );
const currentPage = useFileStore(documentSelectors.getDocumentById(pageId));
const [editorInit, setEditorInit] = React.useState(false);
const [contentInit, setContentInit] = React.useState(false);
- const [isLoadingDetail, setIsLoadingDetail] = React.useState(false);
+ const [phaseUpdateCounter, setPhaseUpdateCounter] = React.useState(0);
const lastLoadedDocIdRef = useRef<string | undefined>(undefined);
+ const initStateRef = useRef<InitState>({
+ phase: 'idle',
+ targetPageId: undefined,
+ });
+
+ // Helper to transition phase and trigger re-render
+ const transitionPhase = React.useCallback((newPhase: InitPhase) => {
+ log(`Transitioning phase: ${initStateRef.current.phase} -> ${newPhase}`);
+ initStateRef.current.phase = newPhase;
+ setPhaseUpdateCounter((n) => n + 1); // Trigger re-render
+ }, []);
// Update editorState in store
useEffect(() => {
@@ -46,12 +75,22 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('onBack', onBack);
useStoreUpdater('parentId', parentId);
- // Fetch full document detail when pageId changes
+ // State machine effect for deterministic initialization
useEffect(() => {
- if (pageId && pageId !== lastLoadedDocIdRef.current) {
- log('PageId changed, fetching detail:', pageId);
- // Immediately show loading state and reset for better UX
- setIsLoadingDetail(true);
+ const state = initStateRef.current;
+
+ // Phase handler functions
+ const handleIdlePhase = () => {
+ // Check if we can start initialization
+ if (!pageId || !editor || !editorInit) {
+ log('idle: Waiting for prerequisites', { editor: !!editor, editorInit, pageId });
+ return;
+ }
+
+ // Transition to waiting-for-data
+ log('idle -> waiting-for-data:', pageId);
+
+ // Reset UI state
setContentInit(false);
storeApi.setState({
currentTitle: '',
@@ -59,25 +98,50 @@ const StoreUpdater = memo<StoreUpdaterProps>(
wordCount: 0,
});
- // Fetch the full document detail
- fetchDocumentDetail(pageId)
- .then(() => {
- log('Document detail fetched successfully for:', pageId);
- })
- .finally(() => {
- log('Setting isLoadingDetail to false');
- setIsLoadingDetail(false);
- });
- }
- }, [pageId, fetchDocumentDetail, storeApi]);
+ transitionPhase('waiting-for-data');
+ };
- // Initialize currentDocId and document metadata after fetch completes
- useEffect(() => {
- if (pageId !== lastLoadedDocIdRef.current && !isLoadingDetail) {
- log('Initializing metadata for pageId:', pageId, {
+ const handleWaitingForDataPhase = () => {
+ // Check for errors
+ if (swrError && !isLoadingDetail) {
+ log('waiting-for-data: Error occurred', swrError);
+ initStateRef.current.error = swrError as Error;
+ storeApi.setState({ isLoadingContent: false });
+ transitionPhase('error');
+ return;
+ }
+
+ // Wait for SWR to finish loading
+ if (isLoadingDetail) {
+ log('waiting-for-data: Still loading...');
+ return;
+ }
+
+ // Check if we have data
+ if (!currentPage) {
+ log('waiting-for-data: No data available yet');
+ return;
+ }
+
+ // Transition to initializing
+ log('waiting-for-data -> initializing');
+ transitionPhase('initializing');
+ };
+
+ const handleInitializingPhase = () => {
+ // Check if already initialized for this pageId
+ if (lastLoadedDocIdRef.current === pageId && currentDocId === pageId) {
+ log('initializing: Already initialized, moving to loading-content');
+ transitionPhase('loading-content');
+ return;
+ }
+
+ // Set metadata
+ log('initializing: Setting metadata for pageId:', pageId, {
hasEditorData: !!currentPage?.editorData,
title: currentPage?.title,
});
+
lastLoadedDocIdRef.current = pageId;
setContentInit(false);
@@ -86,100 +150,156 @@ const StoreUpdater = memo<StoreUpdaterProps>(
currentEmoji: currentPage?.metadata?.emoji,
currentTitle: currentPage?.title || '',
});
- }
- }, [pageId, currentPage, storeApi, isLoadingDetail]);
- // Load content into editor after initialization
- useEffect(() => {
- log('Content loading effect check:', {
- contentInit,
- editorInit,
- hasCurrentPage: !!currentPage,
- hasEditor: !!editor,
- hasEditorData: !!currentPage?.editorData,
- isLoadingDetail,
- pageId,
- });
-
- if (!editorInit || !editor || contentInit || isLoadingDetail) return;
-
- // Defer editor content loading to avoid flushSync warning
- queueMicrotask(() => {
- try {
- log('Loading content for page:', pageId);
-
- // Safety check: ensure we're loading content for the current page
- // This prevents loading old content when currentPage has stale data
- const currentState = storeApi.getState();
- if (currentState.currentDocId && currentState.currentDocId !== pageId) {
- log('Skipping content load - currentDocId mismatch', {
- currentDocId: currentState.currentDocId,
- pageId,
- });
- return;
- }
+ // Transition to loading-content
+ log('initializing -> loading-content');
+ transitionPhase('loading-content');
+ };
+
+ const handleLoadingContentPhase = () => {
+ // Prerequisites check
+ if (!editor || !editorInit || contentInit) {
+ log('loading-content: Waiting', { contentInit, editor: !!editor, editorInit });
+ return;
+ }
- // Helper to calculate word count
- const calculateWordCount = (text: string) =>
- text.trim().split(/\s+/).filter(Boolean).length;
-
- storeApi.setState({ lastUpdatedTime: null });
-
- // Check if editorData is valid and non-empty
- const hasValidEditorData =
- currentPage?.editorData &&
- typeof currentPage.editorData === 'object' &&
- Object.keys(currentPage.editorData).length > 0;
-
- // Load from editorData if available
- if (hasValidEditorData) {
- log('Loading from editorData');
- editor.setDocument('json', JSON.stringify(currentPage.editorData));
- const textContent = currentPage.content || '';
- storeApi.setState({ wordCount: calculateWordCount(textContent) });
- } else if (currentPage?.content && currentPage.content.trim()) {
- log('Loading from content - no valid editorData found');
- // Fallback to content (markdown or plain text from parsed files)
- editor.setDocument('markdown', currentPage.content);
- storeApi.setState({ wordCount: calculateWordCount(currentPage.content) });
- } else if (currentPage?.pages) {
- // Fallback to pages content
- const pagesContent = currentPage.pages
- .map((page) => page.pageContent)
- .join('\n\n')
- .trim();
- if (pagesContent) {
- log('Loading from pages content');
- editor.setDocument('markdown', pagesContent);
- storeApi.setState({ wordCount: calculateWordCount(pagesContent) });
+ // Safety check: Prevent loading stale content
+ const currentState = storeApi.getState();
+ if (currentState.currentDocId && currentState.currentDocId !== pageId) {
+ log('loading-content: currentDocId mismatch, aborting', {
+ currentDocId: currentState.currentDocId,
+ pageId,
+ });
+ initStateRef.current.error = new Error('Document ID mismatch');
+ storeApi.setState({ isLoadingContent: false });
+ transitionPhase('error');
+ return;
+ }
+
+ // Load content (defer to avoid flushSync warning)
+ log('loading-content: Queueing content load');
+
+ queueMicrotask(() => {
+ try {
+ // Re-check state in case pageId changed during microtask
+ if (initStateRef.current.targetPageId !== pageId) {
+ log('loading-content: PageId changed during queue, aborting');
+ return;
+ }
+
+ log('Loading content for page:', pageId);
+
+ // Helper to calculate word count
+ const calculateWordCount = (text: string) =>
+ text.trim().split(/\s+/).filter(Boolean).length;
+
+ storeApi.setState({ lastUpdatedTime: null });
+
+ // Check if editorData is valid and non-empty
+ const hasValidEditorData =
+ currentPage?.editorData &&
+ typeof currentPage.editorData === 'object' &&
+ Object.keys(currentPage.editorData).length > 0;
+
+ // Load from editorData if available
+ if (hasValidEditorData) {
+ log('Loading from editorData');
+ editor.setDocument('json', JSON.stringify(currentPage.editorData));
+ const textContent = currentPage.content || '';
+ storeApi.setState({ wordCount: calculateWordCount(textContent) });
+ } else if (currentPage?.content && currentPage.content.trim()) {
+ log('Loading from content - no valid editorData found');
+ editor.setDocument('markdown', currentPage.content);
+ storeApi.setState({ wordCount: calculateWordCount(currentPage.content) });
+ } else if (currentPage?.pages) {
+ // Fallback to pages content
+ const pagesContent = currentPage.pages
+ .map((page) => page.pageContent)
+ .join('\n\n')
+ .trim();
+ if (pagesContent) {
+ log('Loading from pages content');
+ editor.setDocument('markdown', pagesContent);
+ storeApi.setState({ wordCount: calculateWordCount(pagesContent) });
+ } else {
+ log('Clearing editor - empty pages');
+ editor.setDocument('markdown', ' ');
+ storeApi.setState({ wordCount: 0 });
+ }
} else {
- log('Clearing editor - empty pages');
+ // Empty document or temp page - clear editor with minimal content
+ log('Clearing editor - empty/new page');
editor.setDocument('markdown', ' ');
storeApi.setState({ wordCount: 0 });
}
- } else {
- // Empty document or temp page - clear editor with minimal content
- log('Clearing editor - empty/new page');
- editor.setDocument('markdown', ' ');
- storeApi.setState({ wordCount: 0 });
+
+ setContentInit(true);
+ storeApi.setState({ isLoadingContent: false });
+
+ // Transition to ready
+ log('loading-content -> ready');
+ transitionPhase('ready');
+ } catch (error) {
+ log('Failed to load editor content:', error);
+ storeApi.setState({ isLoadingContent: false });
+ initStateRef.current.error = error as Error;
+ transitionPhase('error');
}
+ });
+ };
- setContentInit(true);
- storeApi.setState({ isLoadingContent: false });
- } catch (error) {
- log('Failed to initialize editor content:', error);
- storeApi.setState({ isLoadingContent: false });
+ const handleErrorPhase = () => {
+ const error = initStateRef.current.error;
+ log('error phase:', error?.message);
+ // Error state is sticky until pageId changes
+ };
+
+ // Reset to idle if pageId changes
+ if (pageId !== state.targetPageId) {
+ log('PageId changed, resetting to idle', { from: state.targetPageId, to: pageId });
+ initStateRef.current = { phase: 'idle', targetPageId: pageId };
+ setContentInit(false);
+ return;
+ }
+
+ // Early exit if already ready
+ if (state.phase === 'ready') return;
+
+ // Execute phase handler
+ switch (state.phase) {
+ case 'idle': {
+ handleIdlePhase();
+ break;
+ }
+ case 'waiting-for-data': {
+ handleWaitingForDataPhase();
+ break;
+ }
+ case 'initializing': {
+ handleInitializingPhase();
+ break;
+ }
+ case 'loading-content': {
+ handleLoadingContentPhase();
+ break;
}
- });
+ case 'error': {
+ handleErrorPhase();
+ break;
+ }
+ }
}, [
- editorInit,
contentInit,
+ currentDocId,
+ currentPage,
editor,
+ editorInit,
+ isLoadingDetail,
pageId,
- currentPage,
+ phaseUpdateCounter,
storeApi,
- isLoadingDetail,
- currentDocId,
+ swrError,
+ transitionPhase,
]);
// Track editor initialization
diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.ts
index 8aee35dfd08..aca5b10d43c 100644
--- a/src/store/file/slices/document/action.ts
+++ b/src/store/file/slices/document/action.ts
@@ -1,6 +1,8 @@
import { createNanoId } from '@lobechat/utils';
+import type { SWRResponse } from 'swr';
import { type StateCreator } from 'zustand/vanilla';
+import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
import { useGlobalStore } from '@/store/global';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
@@ -133,6 +135,10 @@ export interface DocumentAction {
documentId: string,
updates: Partial<LobeDocument>,
) => Promise<void>;
+ /**
+ * SWR hook to fetch document detail with caching and auto-sync to store
+ */
+ useFetchDocumentDetail: (documentId: string | undefined) => SWRResponse<LobeDocument | null>;
}
export const createDocumentSlice: StateCreator<
@@ -706,4 +712,56 @@ export const createDocumentSlice: StateCreator<
set({ localDocumentMap: revertMap }, false, n('revertOptimisticUpdate'));
}
},
+
+ useFetchDocumentDetail: (documentId) => {
+ const swrKey = documentId ? ['documentDetail', documentId] : null;
+
+ return useClientDataSWRWithSync<LobeDocument | null>(
+ swrKey,
+ async () => {
+ if (!documentId) return null;
+
+ const document = await documentService.getDocumentById(documentId);
+ if (!document) {
+ console.warn(`[useFetchDocumentDetail] Document not found: ${documentId}`);
+ return null;
+ }
+
+ // Transform API response to LobeDocument format
+ const fullDocument: LobeDocument = {
+ content: document.content || null,
+ createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),
+ editorData:
+ typeof document.editorData === 'string'
+ ? JSON.parse(document.editorData)
+ : document.editorData || null,
+ fileType: document.fileType,
+ filename: document.title || document.filename || 'Untitled',
+ id: document.id,
+ metadata: document.metadata || {},
+ source: 'document',
+ sourceType: DocumentSourceType.EDITOR,
+ title: document.title || '',
+ totalCharCount: document.content?.length || 0,
+ totalLineCount: 0,
+ updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),
+ };
+
+ return fullDocument;
+ },
+ {
+ focusThrottleInterval: 5000,
+ onData: (document) => {
+ if (!document) return;
+
+ // Auto-sync to localDocumentMap
+ const { localDocumentMap } = get();
+ const newMap = new Map(localDocumentMap);
+ newMap.set(documentId!, document);
+ set({ localDocumentMap: newMap }, false, n('useFetchDocumentDetail/onData'));
+ },
+ revalidateOnFocus: true, // 5 seconds
+ },
+ );
+ },
});