diff --git a/packages/automerge-repo-react-hooks/src/useDocuments.ts b/packages/automerge-repo-react-hooks/src/useDocuments.ts index d10a086a..5ae1f874 100644 --- a/packages/automerge-repo-react-hooks/src/useDocuments.ts +++ b/packages/automerge-repo-react-hooks/src/useDocuments.ts @@ -17,7 +17,6 @@ import { useRepo } from "./useRepo.js" * for the output map. */ export const useDocuments = (idsOrUrls?: DocId[]) => { - const [documents, setDocuments] = useState({} as Record) const repo = useRepo() const ids = useMemo( () => @@ -32,6 +31,16 @@ export const useDocuments = (idsOrUrls?: DocId[]) => { [idsOrUrls] ) const prevIds = useRef([]) + const [documents, setDocuments] = useState(() => { + return ids.reduce((docs, id) => { + const handle = repo.find(id) + const doc = handle.docSync() + if (doc) { + docs[id] = doc + } + return docs + }, {} as Record) + }) useEffect(() => { // These listeners will live for the lifetime of this useEffect diff --git a/packages/automerge-repo-react-hooks/test/useDocuments.test.tsx b/packages/automerge-repo-react-hooks/test/useDocuments.test.tsx index 8211b9fa..51b1ef16 100644 --- a/packages/automerge-repo-react-hooks/test/useDocuments.test.tsx +++ b/packages/automerge-repo-react-hooks/test/useDocuments.test.tsx @@ -62,6 +62,18 @@ describe("useDocuments", () => { ) }) + it("returns a collection of loaded documents immediately, given a list of ids", async () => { + const { documentIds, wrapper } = setup() + const onDocs = vi.fn() + + render(, { wrapper }) + + expect(onDocs).not.toHaveBeenCalledWith({}) + expect(onDocs).toHaveBeenCalledWith( + Object.fromEntries(documentIds.map((id, i) => [id, { foo: i }])) + ) + }) + it("cleans up listeners properly", async () => { const { documentIds, wrapper, repo } = setup() const onDocs = vi.fn()