Skip to content

Commit

Permalink
add tutorial chapter for mutations - fixes #2243
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Apr 15, 2019
1 parent c5b4012 commit b176f93
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
let numbers = [1, 2, 3, 4];
function addNumber() {
numbers.push(numbers.length + 1);
}
$: sum = numbers.reduce((t, n) => t + n, 0);
</script>

<p>{numbers.join(' + ')} = {sum}</p>

<button on:click={addNumber}>
Add a number
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
let numbers = [1, 2, 3, 4];
function addNumber() {
numbers = [...numbers, numbers.length + 1];
}
$: sum = numbers.reduce((t, n) => t + n, 0);
</script>

<p>{numbers.join(' + ')} = {sum}</p>

<button on:click={addNumber}>
Add a number
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Updating arrays and objects
---

Because Svelte's reactivity is triggered by assignments, using array methods like `push` and `splice` won't automatically trigger 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:

```js
function addNumber() {
numbers.push(numbers.length + 1);
numbers = numbers;
}
```

But there's a more *idiomatic* solution:

```js
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.

0 comments on commit b176f93

Please sign in to comment.