Cross Tab Comms
An amazing benefit of storing your application state in SQLite
is that you get cross tab sync mostly for free. Let's take a look at how this works.
Note: no CRDTs or CRRs are required for cross tab sync given all tabs are operating locally against the same database file. Given that, this guide will mostly cover run of the mill SQLite features.
Start by importing the cr-sqlite wasm bundle
then create a database and table to store our demo state.
Now lets stick a row in there.
Next, we'll need a UI to display and update our note. A textarea
has been added to this document further down so let's attach event listeners to it. In the listener we'll write to the database when the textarea changes.
For a sophisticated editor you'd want to save deltas and not the entire document contents on each edit.
Finally, subscribe to database changes. One additional trick we throw in there is to forward db change events to a broadcast channel so other tabs can be made aware when the underlying database has changed.
To see that everything works, open this page in multiple tabs or windows and start typing away into the notepad below. You should see the changes propagate to all tabs.
Doing Better
This showed you the base primitives (db.onUpdate
and BroadcastChannel
) that you can use to keep all tabs in sync. Integration with React, Svelte and other UI frameworks make this vastly simpler.
For example, in React you can do:
const allTodos: Todo[] = useQuery<Todo>(
ctx,
["todo"],
"SELECT * FROM todo ORDER BY id DESC"
).data;
to subscribe a component to a query. This method is used in the todomvc example.