a single store or an array of dependent stores
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.
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
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)
});
Optional
initialValue: TGenerated using TypeDoc
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.