Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte execute function when any of group of variables changes

In Svelte RealWord 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 problem arises when you want to also include variable which is 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?

like image 388
peceps Avatar asked Aug 01 '19 07:08

peceps


Video Answer


2 Answers

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

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

are both 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.

like image 176
Morphyish Avatar answered Sep 20 '22 19:09

Morphyish


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.

like image 31
Serg The Bright Avatar answered Sep 23 '22 19:09

Serg The Bright