How to watch
a value and get its previous and current value?
#14220
Unanswered
HuakunShen
asked this question in
Q&A
Replies: 2 comments
-
You can wrap effects to create custom functions that have this functionality. Something along the lines of: function watch(getter, effectCallback) {
let previous = undefined;
$effect(() => {
const current = getter(); // add $state.snapshot for deep reactivity
const cleanup = effectCallback(previous);
previous = current;
return cleanup;
});
} let value = $state(0);
watch(() => value, previous => {
// ...
}); |
Beta Was this translation helpful? Give feedback.
0 replies
-
I have just recently published an article on a similar note: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I need something like Vue's
watch
function that provide previous and current value in callback.I don't think
$effect
supports this.Currently I maintained an extra
prev
variable$state
.Beta Was this translation helpful? Give feedback.
All reactions