1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/** @jsxImportSource https://esm.sh/react */
import ReactDom from "https://esm.sh/react-dom";
import { createStore } from "https://esm.sh/tinybase";
import { createRemotePersister } from "https://esm.sh/tinybase/persisters/persister-remote";
import { useValue } from "https://esm.sh/tinybase/ui-react";
// The store is automatically persisted on the remote server
const store = createStore();
const persister = createRemotePersister(store, `${window.location.origin}/load`, `${window.location.origin}/save`);
await persister.startAutoLoad({}, {
count: 0,
});
await persister.startAutoSave();
function App() {
// The component will be refreshed each time the store is updated
const count = useValue("count", store);
return (
<main>
<h1>Tinybase Example</h1>
<p>Open this website in two tabs to see the values get synced after a short interval.</p>
<div>
<button
onClick={() => {
// This will triggers an update immediately, then send the result to the server
store.setValue("count", count - 1);
}}
>
-
</button>
<span>{count}</span>
<button
onClick={() => {
store.setValue("count", count + 1);
}}
>
+
</button>
</div>
</main>
);
}
const root = ReactDom.createRoot(document.body);
root.render(<App />);
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 7, 2024