javascript / beginner
Snippet
Immutable Array Updates
In Svelte, reactivity is triggered by assignment. To update an array and notify the UI, you should create a new array using the spread operator instead of just pushing to the existing one.
snippet.js
1
2
3
4
5
let items = ['Apple', 'Banana'];function addItem() {items = [...items, 'Cherry'];}
svelte
Breakdown
1
let items = ['Apple', 'Banana'];
Declares a reactive variable initialized with an array of strings.
2
items = [...items, 'Cherry'];
Creates a new array containing all old items plus a new one, then assigns it back to trigger a UI update.