Skip to content

Svelte 5: asynchronous derived api #13722

@HighFunctioningSociopathSH

Description

Describe the problem

I love the api surrounding the derived store which also allows you to asynchronously update the value of the store and I was wondering whether we can have something like that when working with the new $derived rune. This could prevent usage of $effect rune in many scenarios.

Describe the proposed solution

In the current api of the derived stores, derived takes the dependecy as its first argument, the callback to update the derivedStore as its second and the intialValue as its third argument. The sad part is that it only accepts stores as its first argument. Maybe we can have something similar but with $state or other $derived runes as the dependency. like below

<script lang="ts">
  let condition = $state(true);
  const delayedCondition = $derived.async(condition, (newCondition, set) => {
    const timeout = setTimeout(() => {
      set(newCondition)
    }, 2000)
    return () => {
      clearTimeout(timeout);
    }
  }, condition)
</script>

Where the first argument is the dependency $state or $derived, the second is the callback function and the third is the initial value of the delayedCondition.

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions