Skip to content

Commit 2017af4

Browse files
authored
fix: ensure computed props are cached with derived (#9757)
Fixes #9751
1 parent aaa1797 commit 2017af4

File tree

5 files changed

+50
-1
lines changed

5 files changed

+50
-1
lines changed

.changeset/selfish-tools-hide.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: ensure computed props are cached with derived

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -767,7 +767,18 @@ function serialize_inline_component(node, component_name, context) {
767767
const [, value] = serialize_attribute_value(attribute.value, context);
768768

769769
if (attribute.metadata.dynamic) {
770-
push_prop(b.get(attribute.name, [b.return(value)]));
770+
const contains_call_expression =
771+
Array.isArray(attribute.value) &&
772+
attribute.value.some((n) => {
773+
return n.type === 'ExpressionTag' && n.metadata.contains_call_expression;
774+
});
775+
if (contains_call_expression) {
776+
const id = b.id(context.state.scope.generate(attribute.name));
777+
context.state.init.push(b.var(id, b.call('$.derived', b.thunk(value))));
778+
push_prop(b.get(attribute.name, [b.return(b.call('$.get', id))]));
779+
} else {
780+
push_prop(b.get(attribute.name, [b.return(value)]));
781+
}
771782
} else {
772783
push_prop(b.init(attribute.name, value));
773784
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<script>
2+
let { random } = $props();
3+
</script>
4+
5+
<p>{random}</p>
6+
<p>{random}</p>
7+
<p>{random}</p>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { test } from '../../test';
2+
3+
let math_random = Math.random;
4+
let calls = 0;
5+
6+
export default test({
7+
skip_if_hydrate: 'permanent',
8+
before_test() {
9+
Math.random = function () {
10+
calls++;
11+
return math_random.call(this);
12+
};
13+
},
14+
after_test() {
15+
Math.random = math_random;
16+
calls = 0;
17+
},
18+
test({ assert }) {
19+
assert.equal(calls, 1);
20+
}
21+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
import Child from './Child.svelte';
3+
</script>
4+
5+
<Child random={Math.random().toFixed(2)} />

0 commit comments

Comments
 (0)