-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
Describe the problem
Sometimes a derived value is not only dependent on state but also on its previous value. I propose an addition to the $derived.by API by providing the previous value as a parameter in its callback. $derived.by((previousValue) => { .... })
example code:
export class TicTacToe {
#board = new SvelteMap()
player = $derived.by((lastPlayer) => {
if (this.#board.size) {
return lastPlayer === 'x' ? 'o' : 'x'
} else {
return 'x'
}
})
move(cellId) {
this.#board.set(cellId, this.player);
// this.player = this.player === 'x' ? 'o' : 'x'
// This above line will be avoidable only when previousValue is provided in `$derived.by((previousValue) => {})`
// Otherwise, this.player should be a $state and explicitly updated as above in all the sites it needs to be updated.
}let count = $state(0)
let derivedFromCount = $derived.by((prevValue) => {
if (count < 4) return count * 2
return count + prevValue * 2 // dependent on state AND its previous value.
})Directly referencing the derived variable inside the $derived.by() is not allowed and gives an error A derived value cannot reference itself recursively. So providing it as param is the only option.
This would allow newer patterns to compute derived values not possible before. Currently these values are modelled as state and are explicitly updated in all the sites updates need to happen. With the new API, we can turn them into deriveds and make svelte automatically update it.
Describe the proposed solution
I would like to see the previous value provided as the parameter in the callback of $derived.by((previousValue) => {}). The initial value will be undefined.
Importance
would make my life easier