Reactively Update Array in Svelte
- 1 minute read
The below Svelte component contains a simple list that enumerates the contents of array
and an updateArray
function, which pushes a new number into array
:
<script>
let array = [1, 2, 3];
const updateArray = () => {
array.push(array[array.length - 1] + 1);
}:
</script>
<ul>
{#each array as number}
<li>number</li>
{/each}
</ul>
<button on:click={updateArray}>
Add Array Item
</button>
However, in the above example, when you press the button or otherwise call updateArray
, you’ll discover that the list does not actually reactively update.
Because Svelte’s reactivity is assignment-based, array methods like push
and pop
don’t cause updates.
One simple way to get around this is by assigning the array you’re trying to update to itself, like this:
const updateArray = () => {
array.push(array[array.length - 1] + 1);
array = array;
}:
By replacing the original component’s updateArray
function with the above improved function, the array will update reactively, as intended.
Conclusion
This also applies to some object methods as well.
And Svelte has a great resource on array and object reacitivty that I’d recommend checking out if you’re still having issues.
Anyway, thanks for reading!