From 39c83bd25b6165afb2c40beb1dba20164dafca9e Mon Sep 17 00:00:00 2001 From: Himself65 Date: Thu, 11 May 2023 23:03:11 +0800 Subject: [PATCH] fix: delay setAom on `rootWorkspacesMetadataAtom` (#2271) --- apps/web/src/atoms/index.ts | 28 +++++++++++++++------ apps/web/src/hooks/__tests__/index.spec.tsx | 2 ++ packages/workspace/src/atom.ts | 1 - 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/apps/web/src/atoms/index.ts b/apps/web/src/atoms/index.ts index 5ee5662b47..75ec626579 100644 --- a/apps/web/src/atoms/index.ts +++ b/apps/web/src/atoms/index.ts @@ -40,17 +40,24 @@ rootWorkspacesMetadataAtom.onMount = setAtom => { }).filter((ids): ids is RootWorkspaceMetadata => !!ids); } - setAtom(metadata => { - if (metadata.length === 0) { - const newMetadata = createFirst(); - logger.info('create first workspace', newMetadata); - return newMetadata; - } - return metadata; - }); + const abortController = new AbortController(); + + // next tick to make sure the hydration is correct + const id = setTimeout(() => { + setAtom(metadata => { + if (abortController.signal.aborted) return metadata; + if (metadata.length === 0) { + const newMetadata = createFirst(); + logger.info('create first workspace', newMetadata); + return newMetadata; + } + return metadata; + }); + }, 0); if (environment.isDesktop) { window.apis?.workspace.list().then(workspaceIDs => { + if (abortController.signal.aborted) return; const newMetadata = workspaceIDs.map(w => ({ id: w[0], flavour: WorkspaceFlavour.LOCAL, @@ -63,6 +70,11 @@ rootWorkspacesMetadataAtom.onMount = setAtom => { }); }); } + + return () => { + clearTimeout(id); + abortController.abort(); + }; }; /** diff --git a/apps/web/src/hooks/__tests__/index.spec.tsx b/apps/web/src/hooks/__tests__/index.spec.tsx index 0c8e4f7538..6e477365c9 100644 --- a/apps/web/src/hooks/__tests__/index.spec.tsx +++ b/apps/web/src/hooks/__tests__/index.spec.tsx @@ -202,6 +202,8 @@ describe('useWorkspaces', () => { const { result } = renderHook(() => useAppHelper(), { wrapper: ProviderWrapper, }); + // next tick + await new Promise(resolve => setTimeout(resolve, 100)); { const workspaces = await store.get(workspacesAtom); expect(workspaces.length).toEqual(1); diff --git a/packages/workspace/src/atom.ts b/packages/workspace/src/atom.ts index 16980164b6..405efe7039 100644 --- a/packages/workspace/src/atom.ts +++ b/packages/workspace/src/atom.ts @@ -12,7 +12,6 @@ export type RootWorkspaceMetadata = { // root primitive atom that stores the necessary data for the whole app // be careful when you use this atom, // it should be used only in the root component - /** * root workspaces atom * this atom stores the metadata of all workspaces,