Skip to content

Commit 7ac0d8e

Browse files
trueadmdummdidumm
andauthored
fix: ensure set_text applies coercion to objects before diff (#13542)
* fix: ensure set_text applies coercion to objects before diff * lint * feedback * Update packages/svelte/src/internal/client/render.js Co-authored-by: Simon H <[email protected]> --------- Co-authored-by: Simon H <[email protected]>
1 parent 8148e63 commit 7ac0d8e

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed

.changeset/wet-hats-peel.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 set_text applies coercion to objects before diff

packages/svelte/src/internal/client/render.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,13 @@ export function set_should_intro(value) {
4848
* @returns {void}
4949
*/
5050
export function set_text(text, value) {
51+
// For objects, we apply string coercion (which might make things like $state array references in the template reactive) before diffing
52+
var str = value == null ? '' : typeof value === 'object' ? value + '' : value;
5153
// @ts-expect-error
52-
if (value !== (text.__t ??= text.nodeValue)) {
54+
if (str !== (text.__t ??= text.nodeValue)) {
5355
// @ts-expect-error
54-
text.__t = value;
55-
text.nodeValue = value == null ? '' : value + '';
56+
text.__t = str;
57+
text.nodeValue = str == null ? '' : str + '';
5658
}
5759
}
5860

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { flushSync } from 'svelte';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
test({ assert, target }) {
6+
const btn = target.querySelector('button');
7+
btn?.click();
8+
flushSync();
9+
assert.htmlEqual(target.innerHTML, `<button>add</button><span>1,2,3,4</span>`);
10+
}
11+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<script>
2+
let array = $state([1, 2, 3]);
3+
4+
function addToArray() {
5+
array.push(array.length + 1);
6+
}
7+
</script>
8+
9+
<button onclick={addToArray}>add</button>
10+
11+
<span>{array}</span>

0 commit comments

Comments
 (0)