You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md
+18-5Lines changed: 18 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -2,9 +2,11 @@
2
2
title: Updating arrays and objects
3
3
---
4
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.
5
+
Svelte's reactivity is triggered by assignments. Methods that mutate arrays or objects will not trigger updates by themselves.
6
6
7
-
One way to fix that is to add an assignment that would otherwise be redundant:
7
+
In this example, clicking the "Add a number" button calls the `addNumber` function, which appends a number to the array but doesn't trigger the recalculation of `sum`.
8
+
9
+
One way to fix that is to assign `numbers` to itself to tell the compiler it has changed:
8
10
9
11
```js
10
12
functionaddNumber() {
@@ -13,15 +15,15 @@ function addNumber() {
13
15
}
14
16
```
15
17
16
-
But there's a more idiomatic solution:
18
+
You could also write this more concisely using the ES6 spread syntax:
17
19
18
20
```js
19
21
functionaddNumber() {
20
22
numbers = [...numbers, numbers.length+1];
21
23
}
22
24
```
23
25
24
-
You can use similar patterns to replace `pop`, `shift`, `unshift` and `splice`.
26
+
The same rule applies to array methods such as `pop`, `shift`, and `splice` and to objects methods such as `Map.set`, `Set.add`, etc.
25
27
26
28
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.
27
29
@@ -31,11 +33,22 @@ function addNumber() {
31
33
}
32
34
```
33
35
34
-
A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...
36
+
However, indirect assignments to references such as this...
35
37
36
38
```js
37
39
constfoo=obj.foo;
38
40
foo.bar='baz';
39
41
```
40
42
43
+
or
44
+
45
+
```js
46
+
functionquox(thing) {
47
+
thing.foo.bar='baz';
48
+
}
49
+
quox(obj);
50
+
```
51
+
41
52
...won't trigger reactivity on `obj.foo.bar`, unless you follow it up with `obj = obj`.
53
+
54
+
A simple rule of thumb: the updated variable must directly appear on the left hand side of the assignment.
0 commit comments