-
I want to use |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
For an object that needs to react to outside changes, I would pass a function pointing to state (for read-only state) or a boxed value (so there is a getter/setter - the let doubler = expensiveCreateDoubler({ value: () => value }); export function expensiveCreateDoubler({ value }) {
let double = $derived(value() * 2);
return {
get value() {
return value();
},
get double() {
return double;
}
}
} let doubler = expensiveCreateDoubler({
get value() { return value },
set value(v) { value = v },
}); export function expensiveCreateDoubler(options) {
let double = $derived(options.value * 2);
return {
get value() {
return options.value;
},
set value(value) {
options.value = value;
},
get double() {
return double;
}
}
} (This does not look like good design, though.) Using |
Beta Was this translation helpful? Give feedback.
-
The latest version of the The solution.export function stateLink(getValue) {
let wasLocal = false;
let localState = $state(undefined);
// Choose `localState` as the latest value if the mutation was local
// Otherwise, choose the linked `getValue()` because the change was a reaction
const linkedDerived = $derived.by(() => {
const linkedValue = getValue();
if (wasLocal) {
wasLocal = false;
return localState;
}
return linkedValue;
});
return {
get current() {
return linkedDerived;
},
set current(v) {
wasLocal = true;
localState = v;
},
};
} |
Beta Was this translation helpful? Give feedback.
The latest version of the
$state.link
rune (before it was removed) used a pattern that solves our problem here cleanly.The solution.
The original exa…