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

optimistic-updates.mdx

54 lines2.2 KB

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 button

Rename 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 button

Set 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).

  1. at first, everything is the same (fast update)
  2. 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. ✨