Svelte execute function when any of group of variables changes
Asked Answered
H

2

17

In Svelte RealWorld App there is something like this:

$: query && getData();

This calls REST API when page size or other query parameters change.

I have similar situation for listing entities and do:

$: activePage && sort && pageSize && getData();

This all works well (although the && is a strange construct to say I want to execute getData() when activePage, sort or pageSize changes.

With this approach a problem arises when you want to also include variables which evaluates to falsy.

Example, add searchQuery text:

let searchQuery = "";
$: searchQuery && activePage && sort && pageSize && getData();

Now reactivity does not work since searchQuery evaluates to false.

We can do this:

$: activePage && sort && pageSize && getData();
$: searchQuery, getData();

But with this getData() gets called 2 times.

Does anybody know of better approach for this?

Hid answered 1/8, 2019 at 7:38 Comment(0)
S
33

You can use the , and && syntax with any number of variable and conditions:

$: searchQuery, activePage && sort && pageSize && getData();
// or
$: searchQuery, activePage, sort, pageSize, getData();

Both are valid, and with the second one you won't have an issue if one of the variable is falsy, while the first one allow you to make sure that some of the variable are not falsy.

Satirize answered 1/8, 2019 at 9:52 Comment(2)
Learn about the comma operator there: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Extraversion
Ah, another example of wonderful JS weirdness...Hid
A
15

In order to make things clearer, you can pass the observed variables to a function as arguments:

$: onChange(searchQuery, activePage, sort, pageSize);

function onChange(...args) {
  getData();
}

Thus, you don't have to worry if some variable is falsy.

Aemia answered 26/2, 2021 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.