Skip to content

Commit 374729a

Browse files
committed
add optimistic UI example
1 parent d3008e7 commit 374729a

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

documentation/docs/02-runes/03-$derived.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,32 @@ To exempt a piece of state from being treated as a dependency, use [`untrack`](s
5454

5555
## Overriding derived values
5656

57-
Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them. This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user.
57+
Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them. This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user:
58+
59+
```svelte
60+
<script>
61+
let { post, like } = $props();
62+
63+
let likes = $derived(post.likes);
64+
</script>
65+
66+
<button
67+
onclick={() => {
68+
// increment the `likes` count immediately...
69+
likes += 1;
70+
71+
// and tell the server, which will eventually update `post`
72+
try {
73+
await like();
74+
} catch {
75+
// failed! roll back the change
76+
likes -= 1;
77+
}
78+
}}
79+
>
80+
🧡 {likes}
81+
</button>
82+
```
5883

5984
## Update propagation
6085

0 commit comments

Comments
 (0)