reword to include other objects and transitive mutations

pull/7073/head
gtmnayan 4 years ago committed by GitHub
parent 13e2d22ea3
commit 74dedb5977
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -2,9 +2,11 @@
title: Updating arrays and objects
---
Because Svelte's reactivity is triggered by assignments, using array methods that mutate the array alone, like `push` and `splice`, won't automatically cause updates. For example, clicking the button calls the `addNumber` function, but doesn't trigger the recalculation of `sum` and does not update the rendered page.
Svelte's reactivity is triggered by assignments. Methods that mutate arrays/objects internally will not trigger updates by themselves.
One way to fix that is to add an assignment that would otherwise be redundant:
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` and does not update the rendered page.
One way to fix that would be to assign `numbers` to itself to tell the compiler it has changed:
```js
function addNumber() {
@ -13,7 +15,7 @@ function addNumber() {
}
```
But there's a more idiomatic solution:
You can also get a similar result using the ES6 spread syntax:
```js
function addNumber() {
@ -21,7 +23,7 @@ function addNumber() {
}
```
You can use similar patterns to replace `pop`, `shift`, `unshift` and `splice`.
The same rule applies for other array methods such as `pop`, `shift`, `splice` and for other objects such as `Map.set`.
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.
@ -31,11 +33,22 @@ function addNumber() {
}
```
A simple rule of thumb: the name of the updated variable must appear on the left hand side of the assignment. For example this...
However, indirect assignments to references such as this...
```js
const foo = obj.foo;
foo.bar = 'baz';
```
or
```js
function quox(thing) {
thing.foo.bar = 'baz';
}
quox(obj);
```
...won't trigger reactivity on `obj.foo.bar`, unless you follow it up with `obj = obj`.
A simple rule of thumb: the name of the updated variable must directly appear on the left hand side of the assignment.
Loading…
Cancel
Save