blockcn

Autosave

Save the document to your database or object store.

useAutosave waits for edits to settle, flushes when the page hides or unmounts, and retries after a thrown error. The save function can INSERT the JSON into Postgres, upsert a Supabase row, or PutObject the same JSON to S3. Store the revision next to the row so a later server render can cache by it.

This page's code block is examples/recipes/autosave.ts. pnpm --dir docs typecheck compiles that file and fails if this block drifts.

import type { Editor, JSONContent } from "@tiptap/core";
import { useAutosave } from "@/components/editor/useAutosave";

/**
 * `useAutosave` debounces, flushes on hide/unmount, and retries a failed save.
 * Point `save` at Postgres, Supabase, or S3. This one PUTs the JSON to your API.
 */
export function useDocumentSave(editor: Editor | null, id: string) {
  return useAutosave(editor, async (json: JSONContent) => {
    const response = await fetch(`/api/docs/${id}`, {
      method: "PUT",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(json),
    });
    if (!response.ok) throw new Error(`Save failed (${response.status})`);
  });
}