I think I have a working document cache solution that's actually pretty good.
This commit is contained in:
48
src/context/document/DocumentLoader.tsx
Normal file
48
src/context/document/DocumentLoader.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
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) => r.expand?.secondary,
|
||||
) || [],
|
||||
});
|
||||
}
|
||||
|
||||
fetchDocumentAndRelations();
|
||||
}, [documentId]);
|
||||
|
||||
return children;
|
||||
}
|
||||
Reference in New Issue
Block a user