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

optimistic-actions.mdx

134 lines4.6 KB

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