Open History to see the last commit
1import {Link} from '@tanstack/react-router'
2import {
3 GHLink,
4 HighLightComponent,
5 LinkToArticle,
6 OpenAPIRequestsPanelLink
7} from '/src/components/tutorial'
8
9## Optimistic updates
10
11Besides queries, data mutations also get faster with `tanstack-db`.
12
13Let's check what happens when you rename a project!
14
15<HighLightComponent h_id="editProject">Find the edit button</HighLightComponent>
16
17Rename the project to _"My wonderful project"_. BOOM! It changed instantly
18everywhere.
19
20This is the code btw (it's so tiny 🥺):
21
22```ts
23projectsCollection.update(id, (project) => {
24 project.name = value.name
25})
26```
27
28<GHLink href="https://github.com/fulopkovacs/trytanstackdb.com/blob/013849f87b6ce7ab5dee3873424d8e1012b810fc/src/components/EditableProjectDetails.tsx#L22-L24" />
29
30The 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.
31
32<HighLightComponent h_id="apiLatencyConfigurator">Highlight the API latency configurator button</HighLightComponent>
33
34Set the API latency to 5s and <a href="">reload the page</a>. You'll see that the reload takes some time.
35
36Now rename the project again. It still changes immediately!
37
38The 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 database in the background.
39
40### What happens when the data in the remote db can't be updated?
41
42Let's rename our current project to the name of another existing project (like `Project Beta`).
43
441. At first, everything is the same (fast update)
452. When the HTTP request fails in the background (because all project names
46 must be unique)
47 - The changes are immediately rolled back,
48 - And an error message appears in the top right corner
49 - A new `GET` request to `/api/projects` syncs the local state with the remote database. You can watch this happen in the <OpenAPIRequestsPanelLink>_API Requests_ panel</OpenAPIRequestsPanelLink>
50
51The rule is simple: when an update fails, the mutation is rolled back and the collection's state is synced with the remote data source.
52
53**"Okay, but how does the syncing happen? Is it magic???"**. Glad you asked.
54Everything is magic if you just believe in it; let me show you how it works in
55the next section. ✨