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

optimistic-updates.mdx

54 lines2.2 KB

1import {Link} from '@tanstack/react-router'
2import {
3 GHLink,
4 HighLightComponent,
5 ClearHighlightsButton,
6 LinkToArticle,
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 network latency configurator in the header.
31​
32<HighLightComponent h_id="networkLatencyCofigurator">Highlight the network latency configurator button</HighLightComponent>
33​
34Set the network 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 db 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 a toast error message appears in the top right corner
49​
50When 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>).
51​
52**"Okay, but how does the syncing happen? Is it magic???"**. Glad you asked.
53Everything is magic if you just believe in it, let me show you how it works in
54the next section. ✨