The response

At the heart of Svelte is a powerful responsive system that keeps the DOM in sync with application state — for example, in response to an event.

To demonstrate it, we first need a program that fires an event:

<button on:click={handleClick}>
Copy the code

In the handleClick function, all we need to do is change the value of count:

function handleClick() {
	count += 1;
}
Copy the code

Complete code:

<script>
	let count = 0;

	function handleClick() {
		count += 1;
	}
</script>

<button on:click={handleClick}>
	Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Copy the code

Response to the statement

Svelte automatically updates the DOM when a component’s state changes. Typically, some parts of the component state need to be computed from other parts (such as fullname derived from FirstName and lastName) and recalculated when they change.

For these, we declare this:

let count = 0;
$: doubled = count * 2;
Copy the code

Don’t worry, this looks a little weird, but it’s valid JavaScript, which Svelte interprets as “run this code when the value of any reference changes.” Once you get used to it, you can’t go back.

Let’s implement the double effect in HTML:

<p>{count} doubled is {doubled}</p>
Copy the code

Of course, you could just write {count * 2} in HTML without using a response. Responses become especially valuable when you need to reference them multiple times, or when your values depend on other responses.

Complete code:

<script>
	let count = 0;

	function handleClick() {
		count += 1;
	}
</script>

<button on:click={handleClick}>
	Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Copy the code

We are not limited to response variables — we can run arbitrary statements in the response as well. For example, if the value of count changes, we can print:

$: console.log(`the count is ${count}`);
Copy the code

You can also easily combine statements into a block of code:

: ${console.log(`the count is ${count}`);
	alert(`I SAID THE COUNT IS ${count}`);
}
Copy the code

You can even put $: in front of syntax like judge branches:

$: if (count >= 10) {
	alert(`count is dangerously high! `);
	count = 9;
}
Copy the code

The complete code is as follows:

<script>
	let count = 0;

	$: if (count >= 10) {
		alert(`count is dangerously high! `);
		count = 9;
	}

	function handleClick() {
		count += 1;
	}
</script>

<button on:click={handleClick}>
	Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Copy the code

Update arrays and objects

Because the Svelte response is triggered by assignment, using array methods like push and splice does not automatically cause updates.

One way to solve this problem is to add a code that changes the length of the array:

function addNumber() {
	numbers.push(numbers.length + 1);
	numbers = numbers;
}
Copy the code

But there’s a simpler solution:

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

You can use similar patterns to replace POP, shift, unshift, and concat.

* Assignment to array and object attributes * for example obj.foo+=1 or array[I]=x– works in the same way as assignment to the value itself.

function addNumber() {
	numbers[numbers.length] = numbers.length + 1;
}
Copy the code

A simple rule of thumb: The updated variable name must appear on the left side of the assignment. Like this one:

const foo = obj.foo;
foo.bar = 'baz';
Copy the code

Obj.foo. bar is not updated unless you use obj=obj.

Complete code:

<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>
Copy the code

To get a hands-on look at these features, check out Reactive in the Sevlte tutorial