import {Link} from '@tanstack/react-router' import { GHLink, HighLightComponent, ClearHighlightsButton, LinkToArticle, } from '/src/components/tutorial'
Optimistic updates#
Besides queries, data mutations also get faster with tanstack-db.
Let's check what happens when you rename a project!
Find the edit buttonRename the project to "My wonderful project". BOOM! It changed instantly everywhere.
This is the code btw (it's so tiny 🥺):
projectsCollection.update(id, (project) => {
project.name = value.name
})
The 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.
Highlight the API latency configurator buttonSet the API latency to 5s and reload the page. You'll see that the reload takes some time.
Now rename the project again. It still changes immediately!
The 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.
What happens when the data in the remote db can't be updated?#
Let's rename our current project to the name of another existing project (like Project Beta).
- at first, everything is the same (fast update)
- when the http request fails in the background (because all project names
must be unique)
- the changes are immediately rolled back,
- and a toast error message appears in the top right corner
When an update fails, the mutations are rolled back. Rollbacks work seamlessly even for mutations that involve multiple collections (see the tutorial article on Optimistic Actions).
"Okay, but how does the syncing happen? Is it magic???". Glad you asked. Everything is magic if you just believe in it, let me show you how it works in the next section. ✨