Files
dm-companion/src/context/document/DocumentLoader.tsx
2025-10-11 15:18:15 -07:00

52 lines
1.4 KiB
TypeScript

import { pb } from "@/lib/pocketbase";
import { type AnyDocument, type DocumentId } from "@/lib/types";
import type { RecordModel } from "pocketbase";
import type { ReactNode } from "react";
import { useEffect } from "react";
import { useDocumentCache } from "./hooks";
/**
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
*/
export function DocumentLoader({
documentId,
children,
}: {
documentId: DocumentId;
children: ReactNode;
}) {
const { dispatch } = useDocumentCache();
useEffect(() => {
async function fetchDocumentAndRelations() {
dispatch({
type: "loadingDocument",
docId: documentId,
});
const doc: AnyDocument = await pb
.collection("documents")
.getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
});
dispatch({
type: "setDocumentTree",
doc,
relationships: doc.expand?.relationships_via_primary || [],
relatedDocuments:
doc.expand?.relationships_via_primary?.flatMap(
(r: RecordModel): AnyDocument[] =>
// Note: If there are no entries in the expanded secondaries there
// just won't be an entry instead of an empty list.
r.expand?.secondary ?? [],
) ?? [],
});
}
fetchDocumentAndRelations();
}, [documentId]);
return children;
}