Open History to see the last commit
1import {Link} from '@tanstack/react-router'
2import {
3 GHLink,
4 HighLightComponent,
5 LinkToArticle,
6} from '/src/components/tutorial'
7
8## Optimistic updates
9
10Besides queries, data mutations also get faster with `tanstack-db`.
11
12Let's check what happens when you rename a project!
13
14<HighLightComponent h_id="editProject">Find the edit button</HighLightComponent>
15
16Rename the project to _"My wonderful project"_. BOOM! It changed instantly
17everywhere.
18
19This is the code btw (it's so tiny 🥺):
20
21```ts
22projectsCollection.update(id, (project) => {
23 project.name = value.name
24})
25```
26
27<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/013849f87b6ce7ab5dee3873424d8e1012b810fc/src/components/EditableProjectDetails.tsx#L22-L24" />
28
29The change will be instantaneous even for poor connections. Let's test it! Click the button below to highlight the API latency configurator in the header.
30
31<HighLightComponent h_id="apiLatencyConfigurator">Highlight the API latency configurator button</HighLightComponent>
32
33Set the API latency to 5s and <a href="">reload the page</a>. You'll see that the reload takes some time.
34
35Now rename the project again. It still changes immediately!
36
37The reason why we see the change so fast is that the displayed data is from the cache which gets updated basically instantly, while the changes are synced back to the remote db in the background.
38
39### What happens when the data in the remote db can't be updated?
40
41Let's rename our current project to the name of another existing project (like `Project Beta`).
42
431. at first, everything is the same (fast update)
442. when the http request fails in the background (because all project names
45 must be unique)
46 - the changes are immediately rolled back,
47 - and a toast error message appears in the top right corner
48
49When an update fails, the mutations are rolled back. Rollbacks work seamlessly even for mutations that involve multiple collections (see the tutorial article on <LinkToArticle articleTitle="Optimistic Actions">Optimistic Actions</LinkToArticle>).
50
51**"Okay, but how does the syncing happen? Is it magic???"**. Glad you asked.
52Everything is magic if you just believe in it, let me show you how it works in
53the next section. ✨