Skip to content

Commit 8b828a4

Browse files
stephanietuerktanhauhaubenmccannszabgabgtm-nayan
authored
[docs] clarify array methods that won't trigger reactivity (#7073)
Co-authored-by: Tan Li Hau <[email protected]> Co-authored-by: Ben McCann <[email protected]> Co-authored-by: Gabor Szabo <[email protected]> Co-authored-by: gtmnayan <[email protected]>
1 parent 0ed6ebe commit 8b828a4

File tree

1 file changed

+18
-5
lines changed
  • site/content/tutorial/02-reactivity/04-updating-arrays-and-objects

1 file changed

+18
-5
lines changed

site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
title: Updating arrays and objects
33
---
44

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.
66

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:
810

911
```js
1012
function addNumber() {
@@ -13,15 +15,15 @@ function addNumber() {
1315
}
1416
```
1517

16-
But there's a more idiomatic solution:
18+
You could also write this more concisely using the ES6 spread syntax:
1719

1820
```js
1921
function addNumber() {
2022
numbers = [...numbers, numbers.length + 1];
2123
}
2224
```
2325

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.
2527

2628
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.
2729

@@ -31,11 +33,22 @@ function addNumber() {
3133
}
3234
```
3335

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...
3537

3638
```js
3739
const foo = obj.foo;
3840
foo.bar = 'baz';
3941
```
4042

43+
or
44+
45+
```js
46+
function quox(thing) {
47+
thing.foo.bar = 'baz';
48+
}
49+
quox(obj);
50+
```
51+
4152
...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

Comments
 (0)