-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array reactive: $state([])
and JS []
behave differently Array.push()
#15505
Comments
This is to be expected. When you push an element into a proxied array, then that too becomes a clone from the original and is also proxied. That means mutating the original backing array will not work. This works: function click() {
// order A
let a = [3,4];
array.push(a);
array2.push(a);
a = array.at(-1); // we want to mutate the proxied version
setTimeout(() => {
a[1] = "AAA"; // "4" should change to "AAA"
console.log(array2);
}, 500);
// order B
array.push([5,6]);
const b = array.at(-1);
setTimeout(() => {
b[1] = "BBB"; // "6" should change to "BBB"
}, 500);
} |
The logic here is that I first get the reference to the object and then push it into The issue here is the difference in behavior between the Svelte proxied array and the original JS array. This difference in behavior is not an inevitable consequence of the proxy or unavoidable. It ultimately depends on how Svelte implements the proxy and how the code compiles. |
@Fd929c2CE5fA We just need to document this then. When you push an object into a proxied array, you're not actually pushing that object into the array. Under the hood, we're passing a copy of your array that has also been proxied into the array. |
Maybe the correct usage should be: ...
function click() {
// order A
- const a = [3,4];
+ const a = $state([3,4]);
array.push(a);
... |
Describe the bug
In JS,
Array.push()
should preserve the original object reference.But
$state([])
does not seem to follow that logic.This breaks the expected behavior of Svelte Array reactivity.
Reproduction
Playground
Logs
System Info
Severity
annoyance
The text was updated successfully, but these errors were encountered: