Forms now update documents directly.

This commit is contained in:
2025-07-02 17:36:45 -07:00
parent f27432ef05
commit db4ce36c27
17 changed files with 120 additions and 228 deletions

View File

@@ -1,12 +1,11 @@
import { pb } from "@/lib/pocketbase";
import { type AnyDocument, type DocumentId } from "@/lib/types";
import type { RecordModel } from "pocketbase";
import type { ReactNode } from "react";
import { createContext, useContext, useEffect, useReducer } from "react";
import type { DocumentAction } from "./actions";
import { reducer } from "./reducer";
import { loading, type DocumentState } from "./state";
import { useQueryClient } from "@tanstack/react-query";
import type { RecordModel } from "pocketbase";
type DocumentContextValue = {
state: DocumentState<AnyDocument>;
@@ -27,20 +26,16 @@ export function DocumentProvider({
documentId: DocumentId;
children: ReactNode;
}) {
const queryClient = useQueryClient();
const [state, dispatch] = useReducer(reducer, loading());
useEffect(() => {
async function fetchDocumentAndRelations() {
const doc: AnyDocument = await queryClient.fetchQuery({
queryKey: ["document", documentId],
staleTime: 5 * 60 * 1000, // 5 mintues
queryFn: () =>
pb.collection("documents").getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
}),
});
const doc: AnyDocument = await pb
.collection("documents")
.getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
});
dispatch({
type: "ready",

View File

@@ -11,14 +11,10 @@ export type DocumentAction<D extends AnyDocument> =
relatedDocuments: AnyDocument[];
}
| {
type: "update";
data: D["data"];
type: "setDocument";
doc: AnyDocument;
}
| {
type: "setRelationship";
relationship: Relationship;
}
| {
type: "setRelatedDocument";
doc: AnyDocument;
};

View File

@@ -3,7 +3,6 @@ import type {
AnyDocument,
DocumentId,
Relationship,
RelationshipId,
RelationshipType,
} from "@/lib/types";
import type { DocumentAction } from "./actions";
@@ -43,18 +42,23 @@ export function reducer<D extends AnyDocument>(
>,
};
case "update":
if (state.status === "ready") {
case "setDocument":
return ifStatus("ready", state, (state) => {
if (state.doc.id === action.doc.id) {
return {
...state,
doc: action.doc as D,
};
}
return {
...state,
doc: {
...state.doc,
data: action.data,
relatedDocs: {
...state.relatedDocs,
[action.doc.id]: action.doc,
},
};
} else {
return state;
}
});
case "setRelationship":
return ifStatus("ready", state, (state) => ({
...state,
@@ -63,13 +67,5 @@ export function reducer<D extends AnyDocument>(
[action.relationship.type]: action.relationship,
},
}));
case "setRelatedDocument":
return ifStatus("ready", state, (state) => ({
...state,
relatedDocs: {
...state.relatedDocs,
[action.doc.id]: action.doc,
},
}));
}
}