Skip to content

fix: ensure proxied arrays correctly update their length upon deletions #13549

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

Merged
merged 2 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pink-shirts-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: ensure proxied arrays correctly update their length upon deletions
10 changes: 10 additions & 0 deletions packages/svelte/src/internal/client/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ export function proxy(value, parent = null, prev) {
sources.set(prop, source(UNINITIALIZED));
}
} else {
// When working with arrays, we need to also ensure we update the length when removing
// an indexed property
if (is_proxied_array && typeof prop === 'string') {
var ls = /** @type {Source<number>} */ (sources.get('length'));
var n = Number(prop);

if (Number.isInteger(n) && n < ls.v) {
set(ls, n);
}
}
set(s, UNINITIALIZED);
update_version(version);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
compileOptions: {
dev: true
},

async test({ target, assert, logs }) {
const button = target.querySelector('button');

flushSync(() => {
button?.click();
});

assert.deepEqual(logs, [
'init',
[1, 2, 3, 7],
'update',
[2, 2, 3, 7],
'update',
[2, 3, 3, 7],
'update',
[2, 3, 7, 7],
'update',
[2, 3, 7]
]);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<script>
function createState(init) {
let values = $state(init);

return {
get value() {
return $state.snapshot(values);
},

get workedValues() {
let newValue = [];
for (const value of values) {
if (value === undefined) {
throw new Error('undefined found');
}

newValue.push(value);
}
return newValue;
},

doSplice() {
values.splice(0, 1);
}
};
}

const myState = createState([1, 2, 3, 7]);

$inspect(myState.workedValues);
</script>

<button onclick={() => myState.doSplice()}>Delete</button>