Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

optimistic-actions.mdx

135 lines4.6 KB

1import {Link} from '@tanstack/react-router'
2import {
3 GHLink,
4 HighLightComponent,
5 ClearHighlightsButton,
6} from '/src/components/tutorial'
7​
8## Optimistic Actions
9​
10### Moving task between boards
11​
12In our highly sophisticated todo app, the positions of the todo items are stored in a column of the `projects` table. It's a json array:
13​
14​
15```json
17 "board-1": ["task-1", "task-2", ...],
18 "board-2": [...],
19 "board-2": [...]
21```
22<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/cdf40f6bd48853dcb5775f9405d5ab129336629c/src/db/schema.ts#L38-L41" />
23​
24​
25​
26When new task is created, we need to update two different tables in our database:
271. `todo-items`: we insert the new task's record into this table
281. `projects`: the json array in the `item_positions_in_the_project` column must be updated to reflect the new orders of the tasks on the boards
29​
30### The naive approach
31​
32At first, you might want to do something like this:
33​
34```ts
35todoItemsCollection.insert(/*... */);
36projectsCollection.update(/* ... */);
37```
38​
39There's a problem with this approach: what happens if one of the requests fail? For example:
40​
41- ✅ the new todo item gets inserted successfully,
42- ❌but the project can't be updated for some reason
43 - this means that the changes made to the project will be rolled back
44​
45Oh no! 💀 Now we don't know where the task is on the board.
46​
47### The solution: `createOptimisticAction()`
48​
49At this point, what we want is an action that does the following:
50- optimistically updates both collections in the cache
51- sends one request to the api, that attempts to update both tables (in a db transaction on the backend)
52- rolls back all optimistic changes if any of the tables can't be updated
53​
54This can be all done with optimistic actions:
55​
56```ts
57const createTodoItem = createOptimisticAction({
58 id: "create-todo-item",
59 autoCommit: true,
60 onMutate: (newItemData: CreateTodoItemInput) => {
61 // This insert statement here will not actually trigger
62 // the `onInsert` function we defined when we created
63 // the `todoItemsCollection`.
64 // It'll only update the local cache optimistically.
65 todoItemsCollection.insert({
66 createdAt: new Date(),
67 ...newItemData,
68 priority: 0,
69 });
70​
71 // Just like the `insert()` method above, this will also
72 // not run the `onUpdate` function on the `projectsCollection`.
73 projectsCollection.update(newItemData.projectId, (project) => {
74 project.itemPositionsInTheProject[newItemData.boardId].unshift(
75 newItemData.id,
76 );
77 });
78 },
79 mutationFn: async (newItemData: CreateTodoItemInput) => {
80 // send a fetch request to the server
81 await insertTodoItem({
82 data: newItemData,
83 });
84 // We need to manually sync the data back from the server
85 await todoItemsCollection.utils.refetch();
86 await projectsCollection.utils.refetch();
87 },
88});
89```
90<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/cdf40f6bd48853dcb5775f9405d5ab129336629c/src/components/CreateOrEditTodoItems.tsx#L29-L53" />
91​
92The `insertTodoItem` is basically a `fetch` request to a server endpoint:
93​
94```ts
95export async function insertTodoItem({
96 data,
97}: {
98 data: TodoItemCreateDataType;
99}) {
100 const res = await fetch("/api/todo-items", {
101 method: "POST",
102 headers: {
103 "Content-Type": "application/json",
104 },
105 body: JSON.stringify(data),
106 });
107​
108 if (!res.ok) {
109 throw new Error("Failed to insert todo item");
110 }
111​
112 const response: TodoItemRecord = await res.json();
113​
114 return response;
116```
117<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/cdf40f6bd48853dcb5775f9405d5ab129336629c/src/collections/todoItems.ts#L38-L58" />
118​
119​
120> You can check the backend's endpoint <a target="_blank" href="https://github.com/fulopkovacs/trytanstackdb.com/blob/cdf40f6bd48853dcb5775f9405d5ab129336629c/src/local-api/api.todo-items.ts#L36-L131">in the repo</a> if you're interested.
121​
122Now you can use `createTodoItem()` when you want to insert a new todo items and be sure that the two tables will always be in sync with each other:
123​
124​
125```ts
126createTodoItem({ /* the data of the todo item */ });
127```
128<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/cdf40f6bd48853dcb5775f9405d5ab129336629c/src/collections/todoItems.ts#L38-L58" />
129​
130​
131Read more about optimistic actions <a target="_blank" href="https://tanstack.com/db/latest/docs/guides/mutations#intent-based-mutations-with-custom-actions">in the docs</a>.
132​
133### More complex mutations
134​
135If you need even more control (e.g.: opting out from the optimistic updates, etc.), check out the <a target="_blank" href="https://tanstack.com/db/latest/docs/guides/mutations">Mutations</a> page in the docs.