Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow useDocuments to immediately return already-loaded documents #375

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/automerge-repo-react-hooks/src/useDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { useRepo } from "./useRepo.js"
* for the output map.
*/
export const useDocuments = <T>(idsOrUrls?: DocId[]) => {
const [documents, setDocuments] = useState({} as Record<DocumentId, T>)
const repo = useRepo()
const ids = useMemo(
() =>
Expand All @@ -32,6 +31,16 @@ export const useDocuments = <T>(idsOrUrls?: DocId[]) => {
[idsOrUrls]
)
const prevIds = useRef<DocumentId[]>([])
const [documents, setDocuments] = useState(() => {
return ids.reduce((docs, id) => {
const handle = repo.find<T>(id)
const doc = handle.docSync()
if (doc) {
docs[id] = doc
}
return docs
}, {} as Record<DocumentId, T>)
})

useEffect(() => {
// These listeners will live for the lifetime of this useEffect
Expand Down
12 changes: 12 additions & 0 deletions packages/automerge-repo-react-hooks/test/useDocuments.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ describe("useDocuments", () => {
)
})

it("returns a collection of loaded documents immediately, given a list of ids", async () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sort of duplicates the above test. I wasn't sure if this should be its own test or be folded into the above.

const { documentIds, wrapper } = setup()
const onDocs = vi.fn()

render(<Component idsOrUrls={documentIds} onDocs={onDocs} />, { 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()
Expand Down
Loading