How can I skip the first effect run with createEffect?

I have a createEffect hook that runs when my signal does. Awesome. What I don't want, is for the effect to run when the initial signal value is set. I tried the following without success:
const [getVal, setVal] = createSignal("initial");

let firstEffectHasRun = false;
createEffect(() => {
if (firstEffectHasRun) {
console.log("Boom!");
} else {
firstEffectHasRun = true;
}
});
const [getVal, setVal] = createSignal("initial");

let firstEffectHasRun = false;
createEffect(() => {
if (firstEffectHasRun) {
console.log("Boom!");
} else {
firstEffectHasRun = true;
}
});
I don't get why this doesn't work since firstEffectHasRun should be cached since it's used within the callback.
2 Replies
thetarnav
thetarnav2y ago
that effect is not subscribing to anything, so why would it rerun? you can do this:
let init = true;
createEffect(() => {
// track
const val = value()
// skip initial
if (init) return init = false
// boom
console.log("Boom!")
});
let init = true;
createEffect(() => {
// track
const val = value()
// skip initial
if (init) return init = false
// boom
console.log("Boom!")
});
or use on:
createEffect(on(
// track
value,
// boom
() => console.log("Boom!"),
// skip initial
{ defer: true }
))
createEffect(on(
// track
value,
// boom
() => console.log("Boom!"),
// skip initial
{ defer: true }
))
RATIU5
RATIU5OP2y ago
Completely missed that part when copying over. And your first method worked fine, I was not aware about the on function. My guess is that since I had my subscription within the conditional statement it did not run. It works now, thank you!
Want results from more Discord servers?
Add your server