Skip to content

Commit c83696b

Browse files
committed
regenerate
1 parent 4ca9efa commit c83696b

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

documentation/docs/98-reference/.generated/client-errors.md

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -134,26 +134,31 @@ Reading state that was created inside the same derived is forbidden. Consider us
134134
Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state`
135135
```
136136

137-
This error is thrown in a situation like this:
137+
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:
138138

139139
```svelte
140140
<script>
141-
let count = $state(0);
142-
let multiple = $derived.by(() => {
143-
const result = count * 2;
144-
if (result > 10) {
145-
count = 0;
146-
}
147-
return result;
148-
});
141+
let count = $state(0);
142+
143+
let even = $state(true);
144+
145+
let odd = $derived.by(() => {
146+
if (count % 2 !== 0) even = false;
147+
return !even;
148+
});
149149
</script>
150150
151-
<button onclick={() => count++}>{count} / {multiple}</button>
151+
<button onclick={() => count++}>{count}</button>
152+
153+
<p>{count} is even: {even}</p>
154+
<p>{count} is odd: {odd}</p>
152155
```
153156

154-
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.
157+
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:
158+
159+
```js
160+
let even = $derived(count % 2 === 0);
161+
let odd = $derived(!even);
162+
```
155163

156-
To fix this:
157-
- See if it's possible to refactor your `$derived` such that the update becomes unnecessary
158-
- 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
159-
- 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
164+
If side-effects are unavoidable, use [`$effect`]($effect) instead.

0 commit comments

Comments
 (0)