a way to know if we're currently inside an effect tree
#16366PR for https://github.com/sveltejs/kit/discussions/13897, discussion should happen there.
For a more complete commit history (with lots of explorations and dead ends; also includes some caching ideas) see #13957
pnpm test
and lint the project with pnpm lint
and pnpm check
pnpm changeset
and following the prompts. Changesets that add features should be minor
and those that fix bugs should be patch
. Please prefix changeset messages with feat:
, fix:
, or chore:
.This adds the $effect.allowed
rune, an advanced feature that indicates whether an effect or async derived can be created in the current context. Effects and async deriveds can only be created when a root effect is active, and previously, the only way to know this was to try creating an effect and checking if it threw an error.
Closes #16366.
feat:
, fix:
, chore:
, or docs:
.packages/svelte/src
, add a changeset (npx changeset
).pnpm test
and lint the project with pnpm lint
sveltejs/kit#13986 has this code:
try {
$effect.pre(() => {
// ...
});
} catch {
// ...
}
This is necessary because it needs to use an effect to manage the query cache, and $effect.tracking()
is false
when initialising a component.
Maybe $effect.active()
?
The downside of course is that $effect.tracking()
is already a source of confusion, and having $effect.active()
which is very similar but subtly different will exacerbate that.
nice to have
I like this, why was this rejected previously?
Not sure we discussed it previously? I don't think we encountered a real need for it until now
IIRC #14757 was going to add $effect.active()
, which would indicate that you were inside an effect (or effect root)
Yeah we discussed this before and concluded it might be nice to have but didn't follow through because of the mentioned additional confusion and lack of real need
Perhaps $effect.allowed()
or something would be clearer
If I'm honest I'm still not sure if I really need that. A try { ... } catch { ... }
is almost the same amount of characters with the same outcome for me and avoids adding another API
If I'm honest I'm still not sure if I really need that. A
try { ... } catch { ... }
is almost the same amount of characters with the same outcome for me and avoids adding another API
Maybe I'm misremembering but isn't try catch extremely slow? I agree that it's not the end of the world and we can just use try catch but if it has performance impacts maybe it could be worth adding the new rune
It was slow, many years ago. Nowadays it's equivalent to an additional function call. Worth avoiding in hot code if you can but not something to worry about too much
One thing I'll say in favour of the explicit API is that a try-catch solution only works if you can guarantee the effect itself doesn't throw (which is true in the motivating example, but might not be true everywhere). The additional API is a nuisance though