Skip to content

Commit b4508ea

Browse files
committed
fix: correctly handle closure passed to $derived.by when destructuring
1 parent 3c155e3 commit b4508ea

File tree

6 files changed

+57
-2
lines changed

6 files changed

+57
-2
lines changed

.changeset/grumpy-jars-sparkle.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"svelte": patch
3+
---
4+
5+
fix: correctly handle closure passed to $derived.by when destructuring

packages/svelte/src/compiler/phases/3-transform/client/visitors/javascript-runes.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ export const javascript_visitors_runes = {
301301
declarations.push(
302302
b.declarator(
303303
b.id(object_id),
304-
b.call('$.derived', b.thunk(rune === '$derived.by' ? b.call(value) : value))
304+
b.call('$.derived', rune === '$derived.by' ? value : b.thunk(value))
305305
)
306306
);
307307
declarations.push(
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { test } from '../../test';
2+
import { log } from './log.js';
3+
4+
export default test({
5+
before_test() {
6+
log.length = 0;
7+
},
8+
9+
html: `<button>0</button>`,
10+
11+
async test({ assert, target, window }) {
12+
const btn = target.querySelector('button');
13+
const clickEvent = new window.Event('click', { bubbles: true });
14+
await btn?.dispatchEvent(clickEvent);
15+
16+
assert.htmlEqual(target.innerHTML, `<button>2</button>`);
17+
assert.deepEqual(log, ['create_derived']);
18+
}
19+
});
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/** @type {any[]} */
2+
export const log = [];
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<script>
2+
import {log} from './log.js'
3+
4+
let count = $state(0);
5+
function create_derived() {
6+
log.push('create_derived');
7+
return () => {
8+
return {
9+
get double() {
10+
return count * 2;
11+
}
12+
}
13+
}
14+
}
15+
let {double} = $derived.by(create_derived());
16+
</script>
17+
18+
<button on:click={() => count++}>{double}</button>
Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
<script>
22
let count = $state(0);
3-
let double = $derived.by(() => count * 2);
3+
let other = $state(0);
4+
function create_derived() {
5+
other++;
6+
return () => {
7+
return {
8+
get double() {
9+
return count * 2;
10+
}
11+
}
12+
}
13+
}
14+
let {double} = $derived.by(create_derived());
415
</script>
516

617
<button on:click={() => count++}>{double}</button>

0 commit comments

Comments
 (0)