• A convenience function to create a new store with a state computed from the latest values of dependent stores. Each time the state of one of the dependent stores changes, a provided derive function is called to compute a new, derived state.

    Type Parameters

    Parameters

    • stores: S

      a single store or an array of dependent stores

    • options: AsyncDeriveFn<T, S> | AsyncDeriveOptions<T, S>

      either an object with store options, including a derive function, or the derive function itself directly. The derive function is used to compute a new state based on the latest values of dependent stores.

      Alternatively, this function can accept a second argument, set, to manage asynchronous values. If you return a function from the callback, it will be called when the callback runs again, or the last subscriber unsubscribes.

    • initialValue: T

    Returns ReadableSignal<T>

    Example: synchronous

    const x$ = writable(2);
    const y$ = writable(3);
    const sum$ = derived([x$, $y], ([x, y]) => x + y);

    // will log 5 upon subscription
    sum$.subscribe((value) => {
    console.log(value)
    });

    x$.set(3); // will re-evaluate the `([x, y]) => x + y` function and log 6 as this is the new state of the derived store

    Example: asynchronous

    const x$ = writable(2);
    const y$ = writable(3);

    const sum$ = derived([x$, $y], ([x, y], set) => {
    const timeoutId = setTimeout(() => set(x + y)));
    return () => clearTimeout(timeoutId);
    }, <number>undefined);

    // will log undefined (the default value), then 5 asynchronously
    sum$.subscribe((value) => {
    console.log(value)
    });
  • Type Parameters

    Parameters

    Returns ReadableSignal<T>

Generated using TypeDoc