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