Merge pull request #2424 from sveltejs/gh-2243

add tutorial chapter for mutations
pull/2427/head
Rich Harris 6 years ago committed by GitHub
commit 98dc8adc5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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>

@ -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>

@ -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 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:
```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.
Loading…
Cancel
Save