Async updates in setter of bind:value #18242
Replies: 2 comments
|
If the component is general purpose where you do not know how excactly it will be used, it should provide (bindable) properties and events to be sufficiently flexible. If it is local to your project you can just expose whatever you need. There are no hard rules around any of this, so I would say both approaches are valid since they make sense semantically. It is probably more important that you choose one approach and stick to that throughout your project for consistency. (Also, beware of race conditions when updating values asynchronously.) |
|
The cleanest pattern I've found is to not fight <script lang="ts">
let checked = $state(false);
async function handleChecked(newVal: boolean) {
checked = newVal;
// sync to external source
await syncToStore(checked);
}
</script>
<input type="checkbox" checked={checked} onchange={(e) => handleChecked(e.currentTarget.checked)} />Using If you really need <script lang="ts">
let storeChecked = $state(false);
const boundChecked = $derived({
get: () => storeChecked,
set: async (v: boolean) => {
storeChecked = v;
await pushToRemote(v);
}
});
</script>
<input type="checkbox" bind:checked={boundChecked} />This keeps the |
Uh oh!
There was an error while loading. Please reload this page.
Hi! I have a question about the idiomatic way to handle async state updates with
bind:.Let's say I have a simple wrapper around
<input type="checkbox">:Usage with local state works perfectly fine:
But sometimes the value comes from some external reactive source where updating it requires an async request to the backend.
One possible approach is using function bindings:
However, I'm not sure whether performing side effects / async requests inside a bind setter is considered idiomatic in Svelte.
Another option would be treating the component as controlled and handling updates separately:
But in that case, what’s the point of making
checkedbindable?Also, is it considered normal for a component to support both approaches simultaneously?
For example:
bind:for simple/local stateonChangefor async/server-backed updatesOr is it better to encourage only a single pattern consistently across the component API?
Would appreciate any guidance or examples from Svelte community.
All reactions