Merge branch 'main' into state-onchange

state-onchange
Rich Harris 3 days ago
commit 0fd4d2adcc

@ -52,6 +52,48 @@ Anything read synchronously inside the `$derived` expression (or `$derived.by` f
To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack).
## Overriding derived values
Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them (unless they are declared with `const`). 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:
```svelte
<script>
let { post, like } = $props();
let likes = $derived(post.likes);
async function onclick() {
// increment the `likes` count immediately...
likes += 1;
// and tell the server, which will eventually update `post`
try {
await like();
} catch {
// failed! roll back the change
likes -= 1;
}
}
</script>
<button {onclick}>🧡 {likes}</button>
```
> [!NOTE] Prior to Svelte 5.25, deriveds were read-only.
## Deriveds and reactivity
Unlike `$state`, which converts objects and arrays to [deeply reactive proxies]($state#Deep-state), `$derived` values are left as-is. For example, [in a case like this](/playground/untitled#H4sIAAAAAAAAE4VU22rjMBD9lUHd3aaQi9PdstS1A3t5XvpQ2Ic4D7I1iUUV2UjjNMX431eS7TRdSosxgjMzZ45mjt0yzffIYibvy0ojFJWqDKCQVBk2ZVup0LJ43TJ6rn2aBxw-FP2o67k9oCKP5dziW3hRaUJNjoYltjCyplWmM1JIIAn3FlL4ZIkTTtYez6jtj4w8WwyXv9GiIXiQxLVs9pfTMR7EuoSLIuLFbX7Z4930bZo_nBrD1bs834tlfvsBz9_SyX6PZXu9XaL4gOWn4sXjeyzftv4ZWfyxubpzxzg6LfD4MrooxELEosKCUPigQCMPKCZh0OtQE1iSxcsmdHuBvCiHZXALLXiN08EL3RRkaJ_kDVGle0HcSD5TPEeVtj67O4Nrg9aiSNtBY5oODJkrL5QsHtN2cgXp6nSJMWzpWWGasdlsGEMbzi5jPr5KFr0Ep7pdeM2-TCelCddIhDxAobi1jqF3cMaC1RKp64bAW9iFAmXGIHfd4wNXDabtOLN53w8W53VvJoZLh7xk4Rr3CoL-UNoLhWHrT1JQGcM17u96oES5K-kc2XOzkzqGCKL5De79OUTyyrg1zgwXsrEx3ESfx4Bz0M5UjVMHB24mw9SuXtXFoN13fYKOM1tyUT3FbvbWmSWCZX2Er-41u5xPoml45svRahl9Wb9aasbINJixDZwcPTbyTLZSUsAvrg_cPuCR7s782_WU8343Y72Qtlb8OYatwuOQvuN13M_hJKNfxann1v1U_B1KZ_D_mzhzhz24fw85CSz2irtN9w9HshBK7AQAAA==)...
```svelte
let items = $state([...]);
let index = $state(0);
let selected = $derived(items[index]);
```
...you can change (or `bind:` to) properties of `selected` and it will affect the underlying `items` array. If `items` was _not_ deeply reactive, mutating `selected` would have no effect.
## Update propagation
Svelte uses something called _push-pull reactivity_ — when state is updated, everything that depends on the state (whether directly or indirectly) is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull').

@ -74,6 +74,8 @@ Teardown functions also run when the effect is destroyed, which happens when its
`$effect` automatically picks up any reactive values (`$state`, `$derived`, `$props`) that are _synchronously_ read inside its function body (including indirectly, via function calls) and registers them as dependencies. When those dependencies change, the `$effect` schedules a re-run.
If `$state` and `$derived` are used directly inside the `$effect` (for example, during creation of a [reactive class](https://svelte.dev/docs/svelte/$state#Classes)), those values will _not_ be treated as dependencies.
Values that are read _asynchronously_ — after an `await` or inside a `setTimeout`, for example — will not be tracked. Here, the canvas will be repainted when `color` changes, but not when `size` changes ([demo](/playground/untitled#H4sIAAAAAAAAE31T246bMBD9lZF3pWSlBEirfaEQqdo_2PatVIpjBrDkGGQPJGnEv1e2IZfVal-wfHzmzJyZ4cIqqdCy9M-F0blDlnqArZjmB3f72XWRHVCRw_bc4me4aDWhJstSlllhZEfbQhekkMDKfwg5PFvihMvX5OXH_CJa1Zrb0-Kpqr5jkiwC48rieuDWQbqgZ6wqFLRcvkC-hYvnkWi1dWqa8ESQTxFRjfQWsOXiWzmr0sSLhEJu3p1YsoJkNUcdZUnN9dagrBu6FVRQHAM10sJRKgUG16bXcGxQ44AGdt7SDkTDdY02iqLHnJVU6hedlWuIp94JW6Tf8oBt_8GdTxlF0b4n0C35ZLBzXb3mmYn3ae6cOW74zj0YVzDNYXRHFt9mprNgHfZSl6mzml8CMoLvTV6wTZIUDEJv5us2iwMtiJRyAKG4tXnhl8O0yhbML0Wm-B7VNlSSSd31BG7z8oIZZ6dgIffAVY_5xdU9Qrz1Bnx8fCfwtZ7v8Qc9j3nB8PqgmMWlHIID6-bkVaPZwDySfWtKNGtquxQ23Qlsq2QJT0KIqb8dL0up6xQ2eIBkAg_c1FI_YqW0neLnFCqFpwmreedJYT7XX8FVOBfwWRhXstZrSXiwKQjUhOZeMIleb5JZfHWn2Yq5pWEpmR7Hv-N_wEqT8hEEAAA=)):
```ts
@ -252,6 +254,8 @@ In general, `$effect` is best considered something of an escape hatch — useful
> [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use `$derived.by`.
If you're using an effect because you want to be able to reassign the derived value (to build an optimistic UI, for example) note that [deriveds can be directly overridden]($derived#Overriding-derived-values) as of Svelte 5.25.
You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/playground/untitled#H4sIAAAAAAAACpVRy26DMBD8FcvKgUhtoIdeHBwp31F6MGSJkBbHwksEQvx77aWQqooq9bgzOzP7mGTdIHipPiZJowOpGJAv0po2VmfnDv4OSBErjYdneHWzBJaCjcx91TWOToUtCIEE3cig0OIty44r5l1oDtjOkyFIsv3GINQ_CNYyGegd1DVUlCR7oU9iilDUcP8S8roYs9n8p2wdYNVFm4csTx872BxNCcjr5I11fdgonEkXsjP2CoUUZWMv6m6wBz2x7yxaM-iJvWeRsvSbSVeUy5i0uf8vKA78NIeJLSZWv1I8jQjLdyK4XuTSeIdmVKJGGI4LdjVOiezwDu1yG74My8PLCQaSiroe5s_5C2PHrkVGAgAA)):
```svelte

@ -128,26 +128,33 @@ Cannot set prototype of `$state` object
Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
```
This error is thrown in a situation like this:
This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go:
```svelte
<script>
let count = $state(0);
let multiple = $derived.by(() => {
const result = count * 2;
if (result > 10) {
count = 0;
}
return result;
});
let count = $state(0);
let even = $state(true);
let odd = $derived.by(() => {
even = count % 2 === 0;
return !even;
});
</script>
<button onclick={() => count++}>{count} / {multiple}</button>
<button onclick={() => count++}>{count}</button>
<p>{count} is even: {even}</p>
<p>{count} is odd: {odd}</p>
```
Here, the `$derived` updates `count`, which is `$state` and therefore forbidden to do. It is forbidden because the reactive graph could become unstable as a result, leading to subtle bugs, like values being stale or effects firing in the wrong order. To prevent this, Svelte errors when detecting an update to a `$state` variable.
This is forbidden because it introduces instability: if `<p>{count} is even: {even}</p>` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived:
```js
let count = 0;
// ---cut---
let even = $derived(count % 2 === 0);
let odd = $derived(!even);
```
To fix this:
- See if it's possible to refactor your `$derived` such that the update becomes unnecessary
- Think about why you need to update `$state` inside a `$derived` in the first place. Maybe it's because you're using `bind:`, which leads you down a bad code path, and separating input and output path (by splitting it up to an attribute and an event, or by using [Function bindings](bind#Function-bindings)) makes it possible avoid the update
- If it's unavoidable, you may need to use an [`$effect`]($effect) instead. This could include splitting parts of the `$derived` into an [`$effect`]($effect) which does the updates
If side-effects are unavoidable, use [`$effect`]($effect) instead.

@ -1,5 +1,19 @@
# svelte
## 5.25.0
### Minor Changes
- feat: make deriveds writable ([#15570](https://github.com/sveltejs/svelte/pull/15570))
## 5.24.1
### Patch Changes
- fix: use `get` in constructor for deriveds ([#15300](https://github.com/sveltejs/svelte/pull/15300))
- fix: ensure toStore root effect is connected to correct parent effect ([#15574](https://github.com/sveltejs/svelte/pull/15574))
## 5.24.0
### Minor Changes

@ -84,26 +84,31 @@ See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-long
> Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
This error is thrown in a situation like this:
This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go:
```svelte
<script>
let count = $state(0);
let multiple = $derived.by(() => {
const result = count * 2;
if (result > 10) {
count = 0;
}
return result;
});
let count = $state(0);
let even = $state(true);
let odd = $derived.by(() => {
even = count % 2 === 0;
return !even;
});
</script>
<button onclick={() => count++}>{count} / {multiple}</button>
<button onclick={() => count++}>{count}</button>
<p>{count} is even: {even}</p>
<p>{count} is odd: {odd}</p>
```
Here, the `$derived` updates `count`, which is `$state` and therefore forbidden to do. It is forbidden because the reactive graph could become unstable as a result, leading to subtle bugs, like values being stale or effects firing in the wrong order. To prevent this, Svelte errors when detecting an update to a `$state` variable.
This is forbidden because it introduces instability: if `<p>{count} is even: {even}</p>` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived:
```js
let even = $derived(count % 2 === 0);
let odd = $derived(!even);
```
To fix this:
- See if it's possible to refactor your `$derived` such that the update becomes unnecessary
- Think about why you need to update `$state` inside a `$derived` in the first place. Maybe it's because you're using `bind:`, which leads you down a bad code path, and separating input and output path (by splitting it up to an attribute and an event, or by using [Function bindings](bind#Function-bindings)) makes it possible avoid the update
- If it's unavoidable, you may need to use an [`$effect`]($effect) instead. This could include splitting parts of the `$derived` into an [`$effect`]($effect) which does the updates
If side-effects are unavoidable, use [`$effect`]($effect) instead.

@ -2,7 +2,7 @@
"name": "svelte",
"description": "Cybernetically enhanced web apps",
"license": "MIT",
"version": "5.24.0",
"version": "5.25.0",
"type": "module",
"types": "./types/index.d.ts",
"engines": {

@ -1673,9 +1673,9 @@ function extract_type_and_comment(declarator, state, path) {
const match = /@type {(.+)}/.exec(comment_node.value);
if (match) {
// try to find JSDoc comments after a hyphen `-`
const jsdocComment = /@type {.+} (?:\w+|\[.*?\]) - (.+)/.exec(comment_node.value);
if (jsdocComment) {
cleaned_comment += jsdocComment[1]?.trim();
const jsdoc_comment = /@type {.+} (?:\w+|\[.*?\]) - (.+)/.exec(comment_node.value);
if (jsdoc_comment) {
cleaned_comment += jsdoc_comment[1]?.trim();
}
return {
type: match[1],

@ -21,10 +21,6 @@ export function validate_assignment(node, argument, state) {
const binding = state.scope.get(argument.name);
if (state.analysis.runes) {
if (binding?.kind === 'derived') {
e.constant_assignment(node, 'derived state');
}
if (binding?.node === state.analysis.props_id) {
e.constant_assignment(node, '$props.id()');
}
@ -38,25 +34,6 @@ export function validate_assignment(node, argument, state) {
e.snippet_parameter_assignment(node);
}
}
if (
argument.type === 'MemberExpression' &&
argument.object.type === 'ThisExpression' &&
(((argument.property.type === 'PrivateIdentifier' || argument.property.type === 'Identifier') &&
state.derived_state.some(
(derived) =>
derived.name === /** @type {PrivateIdentifier | Identifier} */ (argument.property).name &&
derived.private === (argument.property.type === 'PrivateIdentifier')
)) ||
(argument.property.type === 'Literal' &&
argument.property.value &&
typeof argument.property.value === 'string' &&
state.derived_state.some(
(derived) =>
derived.name === /** @type {Literal} */ (argument.property).value && !derived.private
)))
) {
e.constant_assignment(node, 'derived state');
}
}
/**
@ -81,7 +58,6 @@ export function validate_no_const_assignment(node, argument, scope, is_binding)
} else if (argument.type === 'Identifier') {
const binding = scope.get(argument.name);
if (
binding?.kind === 'derived' ||
binding?.declaration_kind === 'import' ||
(binding?.declaration_kind === 'const' && binding.kind !== 'each')
) {
@ -96,12 +72,7 @@ export function validate_no_const_assignment(node, argument, scope, is_binding)
// );
// TODO have a more specific error message for assignments to things like `{:then foo}`
const thing =
binding.declaration_kind === 'import'
? 'import'
: binding.kind === 'derived'
? 'derived state'
: 'constant';
const thing = binding.declaration_kind === 'import' ? 'import' : 'constant';
if (is_binding) {
e.constant_binding(node, thing);

@ -11,7 +11,9 @@ export function MemberExpression(node, context) {
if (node.property.type === 'PrivateIdentifier') {
const field = context.state.private_state.get(node.property.name);
if (field) {
return context.state.in_constructor ? b.member(node, 'v') : b.call('$.get', node);
return context.state.in_constructor && (field.kind === 'raw_state' || field.kind === 'state')
? b.member(node, 'v')
: b.call('$.get', node);
}
}

@ -6,6 +6,12 @@ import {
} from '../internal/client/reactivity/effects.js';
import { get, writable } from './shared/index.js';
import { createSubscriber } from '../reactivity/create-subscriber.js';
import {
active_effect,
active_reaction,
set_active_effect,
set_active_reaction
} from '../internal/client/runtime.js';
export { derived, get, readable, readonly, writable } from './shared/index.js';
@ -39,19 +45,34 @@ export { derived, get, readable, readonly, writable } from './shared/index.js';
* @returns {Writable<V> | Readable<V>}
*/
export function toStore(get, set) {
let init_value = get();
var effect = active_effect;
var reaction = active_reaction;
var init_value = get();
const store = writable(init_value, (set) => {
// If the value has changed before we call subscribe, then
// we need to treat the value as already having run
let ran = init_value !== get();
var ran = init_value !== get();
// TODO do we need a different implementation on the server?
const teardown = effect_root(() => {
render_effect(() => {
const value = get();
if (ran) set(value);
var teardown;
// Apply the reaction and effect at the time of toStore being called
var previous_reaction = active_reaction;
var previous_effect = active_effect;
set_active_reaction(reaction);
set_active_effect(effect);
try {
teardown = effect_root(() => {
render_effect(() => {
const value = get();
if (ran) set(value);
});
});
});
} finally {
set_active_reaction(previous_reaction);
set_active_effect(previous_effect);
}
ran = true;

@ -4,5 +4,5 @@
* The current version, as set in package.json.
* @type {string}
*/
export const VERSION = '5.24.0';
export const VERSION = '5.25.0';
export const PUBLIC_VERSION = '5';

@ -1,8 +0,0 @@
import { test } from '../../test';
export default test({
error: {
code: 'constant_assignment',
message: 'Cannot assign to derived state'
}
});

@ -1,5 +0,0 @@
<script>
const a = $state(0);
let b = $derived(a);
b = 1;
</script>

@ -1,8 +0,0 @@
import { test } from '../../test';
export default test({
error: {
code: 'constant_binding',
message: 'Cannot bind to derived state'
}
});

@ -1,6 +0,0 @@
<script>
let a = $state(0);
let b = $derived({ a });
</script>
<input type="number" bind:value={b} />

@ -1,8 +0,0 @@
import { test } from '../../test';
export default test({
error: {
code: 'constant_assignment',
message: 'Cannot assign to derived state'
}
});

@ -1,10 +0,0 @@
<script>
class Counter {
count = $state();
#doubled = $derived(this.count * 2);
nope() {
this.#doubled += 1;
}
}
</script>

@ -1,8 +0,0 @@
import { test } from '../../test';
export default test({
error: {
code: 'constant_assignment',
message: 'Cannot assign to derived state'
}
});

@ -1,10 +0,0 @@
<script>
class Counter {
count = $state();
#doubled = $derived(this.count * 2);
nope() {
this.#doubled++;
}
}
</script>

@ -1,8 +0,0 @@
import { test } from '../../test';
export default test({
error: {
code: 'constant_assignment',
message: 'Cannot assign to derived state'
}
});

@ -1,5 +0,0 @@
<script>
const a = $state(0);
let b = $derived(a);
b++;
</script>

@ -0,0 +1,5 @@
import { test } from '../../test';
export default test({
html: `<p>state,derived state,derived.by derived state</p>`
});

@ -0,0 +1,18 @@
<script>
class Foo {
#state = $state('state')
#derived = $derived('derived ' + this.#state);
#derivedBy = $derived.by(() => {
return 'derived.by ' + this.#derived
});
initial
constructor() {
this.initial = [this.#state, this.#derived, this.#derivedBy]
}
}
const foo = new Foo()
</script>
<p>{foo.initial}</p>

@ -0,0 +1,16 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
async test({ assert, target }) {
let btn = target.querySelector('button');
btn?.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
`<div>Count 1!</div><div>Count from store 1!</div><button>Add 1</button>`
);
}
});

@ -0,0 +1,11 @@
<script>
import { toStore } from "svelte/store";
let counter = $state(0);
const count = toStore(() => counter, value => counter = value);
</script>
<div>Count {counter}!</div>
<div>Count from store {$count}!</div>
<button onclick={() => counter+=1}>Add 1</button>

@ -0,0 +1,46 @@
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<input type="range"><input type="range"><p>0 * 2 = 0</p>
`,
ssrHtml: `
<input type="range" value="0"><input type="range" value="0"><p>0 * 2 = 0</p>
`,
test({ assert, target, window }) {
const [input1, input2] = target.querySelectorAll('input');
flushSync(() => {
input1.value = '10';
input1.dispatchEvent(new window.Event('input', { bubbles: true }));
});
assert.htmlEqual(
target.innerHTML,
`<input type="range"><input type="range"><p>10 * 2 = 20</p>`
);
flushSync(() => {
input2.value = '99';
input2.dispatchEvent(new window.Event('input', { bubbles: true }));
});
assert.htmlEqual(
target.innerHTML,
`<input type="range"><input type="range"><p>10 * 2 = 99</p>`
);
flushSync(() => {
input1.value = '20';
input1.dispatchEvent(new window.Event('input', { bubbles: true }));
});
assert.htmlEqual(
target.innerHTML,
`<input type="range"><input type="range"><p>20 * 2 = 40</p>`
);
}
});

@ -0,0 +1,9 @@
<script>
let count = $state(0);
let double = $derived(count * 2);
</script>
<input type="range" bind:value={count} />
<input type="range" bind:value={double} />
<p>{count} * 2 = {double}</p>

@ -1,14 +0,0 @@
[
{
"code": "constant_assignment",
"message": "Cannot assign to derived state",
"start": {
"column": 3,
"line": 6
},
"end": {
"column": 29,
"line": 6
}
}
]

@ -1,9 +0,0 @@
<script>
class Test{
der = $derived({ test: 0 });
set test(v){
this["der"] = { test: 45 };
}
}
</script>

@ -1,14 +0,0 @@
[
{
"code": "constant_assignment",
"message": "Cannot assign to derived state",
"start": {
"column": 3,
"line": 6
},
"end": {
"column": 27,
"line": 6
}
}
]

@ -1,9 +0,0 @@
<script>
class Test{
#der = $derived({ test: 0 });
set test(v){
this.#der = { test: 45 };
}
}
</script>

@ -1,14 +0,0 @@
[
{
"code": "constant_assignment",
"message": "Cannot assign to derived state",
"start": {
"column": 3,
"line": 6
},
"end": {
"column": 26,
"line": 6
}
}
]

@ -1,9 +0,0 @@
<script>
class Test{
der = $derived({ test: 0 });
set test(v){
this.der = { test: 45 };
}
}
</script>
Loading…
Cancel
Save