Skip to content

Commit 98dc8ad

Browse files
authored
Merge pull request sveltejs#2424 from sveltejs/sveltejsgh-2243
add tutorial chapter for mutations
2 parents c5b4012 + d66b1d9 commit 98dc8ad

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<script>
2+
let numbers = [1, 2, 3, 4];
3+
4+
function addNumber() {
5+
numbers.push(numbers.length + 1);
6+
}
7+
8+
$: sum = numbers.reduce((t, n) => t + n, 0);
9+
</script>
10+
11+
<p>{numbers.join(' + ')} = {sum}</p>
12+
13+
<button on:click={addNumber}>
14+
Add a number
15+
</button>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<script>
2+
let numbers = [1, 2, 3, 4];
3+
4+
function addNumber() {
5+
numbers = [...numbers, numbers.length + 1];
6+
}
7+
8+
$: sum = numbers.reduce((t, n) => t + n, 0);
9+
</script>
10+
11+
<p>{numbers.join(' + ')} = {sum}</p>
12+
13+
<button on:click={addNumber}>
14+
Add a number
15+
</button>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
title: Updating arrays and objects
3+
---
4+
5+
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.
6+
7+
One way to fix that is to add an assignment that would otherwise be redundant:
8+
9+
```js
10+
function addNumber() {
11+
numbers.push(numbers.length + 1);
12+
numbers = numbers;
13+
}
14+
```
15+
16+
But there's a more *idiomatic* solution:
17+
18+
```js
19+
function addNumber() {
20+
numbers = [...numbers, numbers.length + 1;]
21+
}
22+
```
23+
24+
You can use similar patterns to replace `pop`, `shift`, `unshift` and `splice`.
25+
26+
> 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 commit comments

Comments
 (0)