Reactivity /
Updating arrays and objects
a. Basics b. Adding data c. Dynamic attributes d. Styling e. Nested components f. HTML tags g. Making an app a. Assignments b. Declarations c. Statements d. Updating arrays and objects a. Declaring props b. Default values c. Spread props a. If blocks b. Else blocks c. Else-if blocks d. Each blocks e. Keyed each blocks f. Await blocks a. DOM events b. Inline handlers c. Event modifiers d. Component events e. Event forwarding f. DOM event forwarding a. Text inputs b. Numeric inputs c. Checkbox inputs d. Group inputs e. Textarea inputs f. Select bindings g. Select multiple h. Contenteditable bindings i. Each block bindings j. Media elements k. Dimensions l. This m. Component bindings a. onMount b. onDestroy c. beforeUpdate and afterUpdate d. tick a. Writable stores b. Auto-subscriptions c. Readable stores d. Derived stores e. Custom stores f. Store bindings a. Tweened b. Spring a. The transition directive b. Adding parameters c. In and out d. Custom CSS transitions e. Custom JS transitions f. Transition events g. Local transitions h. Deferred transitions a. The animate directive a. The use directive b. Adding parameters a. The class directive b. Shorthand class directive a. Slots b. Slot fallbacks c. Named slots d. Checking for slot content e. Slot props a. setContext and getContext a. <svelte:self> b. <svelte:component> c. <svelte:window> d. <svelte:window> bindings e. <svelte:body> f. <svelte:head> g. <svelte:options> a. Sharing code b. Exports a. The @debug tag a. Congratulations!
Because Svelte's reactivity is triggered by assignments, using array methods like push
and splice
won't automatically cause updates. For example, clicking the button doesn't do anything.
One way to fix that is to add an assignment that would otherwise be redundant:
function addNumber ( ) {
numbers. push ( numbers. length + 1 ) ;
numbers = numbers;
}
But there's a more idiomatic solution:
function addNumber ( ) {
numbers = [ ... numbers, numbers. length + 1 ] ;
}
You can use similar patterns to replace pop
, shift
, unshift
and splice
.
Assignments to properties of arrays and objects — e.g. obj.foo += 1
or array[i] = x
— work the same way as assignments to the values themselves.
function addNumber ( ) {
numbers[ numbers. length] = numbers. length + 1 ;
}
A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...
const foo = obj. foo;
foo. bar = 'baz' ;
...won't update references to obj.foo.bar
, unless you follow it up with obj = obj
.
Show me