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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With