Updating arrays and objects

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:

  1. function addNumber() {
  2. numbers.push(numbers.length + 1);
  3. numbers = numbers;
  4. }

But there’s a more idiomatic solution:

  1. function addNumber() {
  2. numbers = [...numbers, numbers.length + 1];
  3. }

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.

  1. function addNumber() {
  2. numbers[numbers.length] = numbers.length + 1;
  3. }