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?
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.