From 8b828a43011bb5fe5b7fe03001f06fba1d999b21 Mon Sep 17 00:00:00 2001 From: Stephanie Tuerk Date: Tue, 17 May 2022 13:26:27 -0400 Subject: [PATCH] [docs] clarify array methods that won't trigger reactivity (#7073) Co-authored-by: Tan Li Hau Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> Co-authored-by: Gabor Szabo Co-authored-by: gtmnayan <50981692+gtm-nayan@users.noreply.github.com> --- .../04-updating-arrays-and-objects/text.md | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md index 20d0f05eeb..a298d1d1bb 100644 --- a/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md +++ b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md @@ -2,9 +2,11 @@ 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. +Svelte's reactivity is triggered by assignments. Methods that mutate arrays or objects 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`. + +One way to fix that is 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 could also write this more concisely 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 to array methods such as `pop`, `shift`, and `splice` and to objects methods such as `Map.set`, `Set.add`, etc. 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 updated variable must directly appear on the left hand side of the assignment. \ No newline at end of file