How to check if a $state
has changed
#15269
-
I have an modal component library that receives an I would like to run a function everytime the $effect(() => {
// This runs on initial mount as well
console.log(Date.now(), isOpen);
}); Would there be a better solution than this? // This works, but the boilerplate does not seem ideal:
let isOpened = isOpen;
$effect(() => {
if (isOpened !== isOpen) console.log('Has toggled at', Date.now());
isOpened = isOpen;
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There's nothing wrong with that boilerplate. Just think about the definition of "has changed". It means "its value went from one to another". In software terms, it means you must compare the current value with the previous one. What you call boilerplate is the exact definition of what you're after. You can either encapsulate this in a reusable class, or you can use the Also, to answer the question, you can exchange one boilerplate for another: let firstRun = true;
$effect(() => {
// This runs on initial mount as well
isOpen;
if (firstRun) {
firstRun = false;
return;
}
console.log(Date.now(), isOpen);
}); Too bloated. Not superior at all. |
Beta Was this translation helpful? Give feedback.
There's nothing wrong with that boilerplate. Just think about the definition of "has changed". It means "its value went from one to another". In software terms, it means you must compare the current value with the previous one. What you call boilerplate is the exact definition of what you're after.
You can either encapsulate this in a reusable class, or you can use the
Previous
class from@svecosystem/runed
sourceAlso, to answer the question, you can exchange one boilerplate for another:
Too bloated. Not sup…