Open History to see the last commit
1import { useEffect } from "react";
2import { toast } from "sonner";
3
4import { subscribeToAppActions } from "@/lib/app-actions";
5import type { AppAction } from "@/lib/app-actions";
6
7const FAILED: { [T in AppAction["type"]]?: (action: Extract<AppAction, { type: T }>) => string } = {
8 "note.created": () => "Couldn't create the note",
9 "note.edited": () => "Couldn't save the note",
10 "note.pinned": (action) => (action.pinned ? "Couldn't pin the note" : "Couldn't unpin the note"),
11 "note.moved": () => "Couldn't move the note",
12 "note.deleted": () => "Couldn't delete the note",
13 "note.restored": () => "Couldn't recover the note",
14 "folder.renamed": () => "Couldn't rename the folder",
15 "account.updated": () => "Couldn't save your settings",
16};
17
18/**
19 * When the server rejects a change, TanStack DB has already rolled it back;
20 * this says so, with the server's reason.
21 */
22export function useRollbackToasts() {
23 useEffect(
24 () =>
25 subscribeToAppActions((event) => {
26 if (event.status !== "rolled-back") return;
27 const title = (FAILED[event.type] as ((action: AppAction) => string) | undefined)?.(event);
28 const description = `${event.error?.message ?? "The server rejected it."} The change was undone.`;
29 // One failed save also undoes the edits queued behind it: show one toast for all of them.
30 toast.error(title ?? "Couldn't save the change", {
31 id: `${title}|${description}`,
32 description,
33 });
34 }),
35 [],
36 );
37}