From b176f9370a6448f89fd8c98e079d6e5949c137b1 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 15 Apr 2019 11:23:29 -0400 Subject: [PATCH] add tutorial chapter for mutations - fixes #2243 --- .../app-a/App.svelte | 15 +++++++++++ .../app-b/App.svelte | 15 +++++++++++ .../04-updating-arrays-and-objects/text.md | 26 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-a/App.svelte create mode 100644 site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-b/App.svelte create mode 100644 site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md diff --git a/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-a/App.svelte b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-a/App.svelte new file mode 100644 index 000000000000..74b11d2399d1 --- /dev/null +++ b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-a/App.svelte @@ -0,0 +1,15 @@ + + +

{numbers.join(' + ')} = {sum}

+ + \ No newline at end of file diff --git a/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-b/App.svelte b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-b/App.svelte new file mode 100644 index 000000000000..3c2111712e04 --- /dev/null +++ b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/app-b/App.svelte @@ -0,0 +1,15 @@ + + +

{numbers.join(' + ')} = {sum}

+ + \ No newline at end of file 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 new file mode 100644 index 000000000000..6908ec7c9906 --- /dev/null +++ b/site/content/tutorial/02-reactivity/04-updating-arrays-and-objects/text.md @@ -0,0 +1,26 @@ +--- +title: Updating arrays and objects +--- + +Because Svelte's reactivity is triggered by assignments, using array methods like `push` and `splice` won't automatically trigger updates. For example, clicking the button doesn't do anything. + +One way to fix that is to add an assignment that would otherwise be redundant: + +```js +function addNumber() { + numbers.push(numbers.length + 1); + numbers = numbers; +} +``` + +But there's a more *idiomatic* solution: + +```js +function addNumber() { + numbers = [...numbers, numbers.length + 1;] +} +``` + +You can use similar patterns to replace `pop`, `shift`, `unshift` and `splice`. + +> 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. \ No newline at end of file