-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
Describe the problem
Imagine this:
You have a .svelte.js/ts file that exports some functions. In these functions, you want to pass a $state or $derived value and use it inside of an $effect, $derived, or something else where you want to keep the reactivity of the value; maybe you want to save the $state's value to a database or external resource as it updates, watch the value for changes and do something when it does change, etc. However, to do that, you have to put the $state value in a callback (or getter/setter object) in the parameters of the function. This feels rather clunky and un-Svelte like. Here's an example of what I mean.
Describe the proposed solution
While there aren't too many good solutions I've thought of, one that stood out to me was to make parameters that accept state values have a name prefixed with a $; the only problem I could see with this is that it may cause some confusion with stores. Examples:
Before
After:
export function watch($value, callback){
let previous = $value;
let dispose = $effect.root(()=>{
$effect(()=>{
let v = $value;
callback(v,previous);
previous = v;
});
});
return dispose;
}
export function syncWithDB($value){
watch($value,(updated)=>{
doDatabaseStuffWithNewData(updated);
})
}Some other solutions I've thought of, but don't feel would entirely fit Svelte include:
- Making functions that use
$stateful values have a$prefixing their name- This makes it harder to have a function that takes
$stateful values as a few parameters instead of all of its parameters. - This would basically make it possible to create new runes, which, in my opinion, kind of takes away some of the magic and simplicity of runes
- This makes it harder to have a function that takes
- Stating which values are meant to be
$states using types- This just feels wrong if you are using vanilla JS. Using JSDoc (if you don't use TS) wouldn't feel good at all, not to mention it'd probably be difficult to implement in the compiler.
- This has basically already been rejected in TS Types for Svelte 5
$statereactivityΒ #11546 and Can we have specific types for reactive state in Svelte 5?Β #13267
- Using comments, a la
@ts-check/@ts-ignore(example)- This feels a little clunky and is also probably difficult to implement in the compiler.
- Using
$statefor the default parameters (example:function foo(value=$state())orfunction bar(value=$state)- This feels somewhat awkward and can be unwanted if the function needs a different default parameter, if the latter option were to be chosen.
Importance
would make my life easier