Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add tutorial chapter for mutations #2424

Merged
merged 2 commits into from
Apr 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
let numbers = [1, 2, 3, 4];

function addNumber() {
numbers.push(numbers.length + 1);
}

$: sum = numbers.reduce((t, n) => t + n, 0);
</script>

<p>{numbers.join(' + ')} = {sum}</p>

<button on:click={addNumber}>
Add a number
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
let numbers = [1, 2, 3, 4];

function addNumber() {
numbers = [...numbers, numbers.length + 1];
}

$: sum = numbers.reduce((t, n) => t + n, 0);
</script>

<p>{numbers.join(' + ')} = {sum}</p>

<button on:click={addNumber}>
Add a number
</button>
Original file line number Diff line number Diff line change
@@ -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 cause 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.