3 ms·
I’ve been using Svelte for several years, but haven’t had much time to dive into the many changes in 5. Maybe someone here can shed light on something about ru
by tobr 2y ago
I’ve been using Svelte for several years, but haven’t had much time to dive into the many changes in 5.
Maybe someone here can shed light on something about runes that feels very off to me. The rune is on the wrong side of the equal sign? Like:
let counter = $state(0);
Looks like a reactive value assigned to a variable, but that’s not at all what’s going on. It’s actually a reactive variable initialized to 0. So, for example, despite what you’d expect you can’t even move the $state call into a utility function if you’d have some reason to. Very counterintuitive to me, and not really touched upon in the docs as far as I’ve seen, but I have to assume there’s some practical reason why they did it this way.
I remember Svelte 2 (or 1? Can’t remember) had some weird things like this as well, where you’d think you could do something based on your experience from JavaScript but it just wasn’t supported. The label syntax in Svelte 3 was pretty brilliant because it was a clear indication that you shouldn’t expect normal JS rules to apply. It did have other problems that they appear to have fixed though.
- jakelazaroff 2y agoHave you tried it out? You can definitely move that $state call into a utility function (or a class field, or another file, etc).
- tobr 2y agoI can’t do this: const createCounter = () => $state(0); let counter = createCounter(); > $state(...) can only be used as a variable declaration initializer or a class field https://svelte.dev/e/state_invalid_placement https://svelte.dev/e/state_invalid_placement (state_invalid_placement) It has to be part of a variable initialization even though it looks like it’s creating a value.
- d1sxeyes 2y agoThat's correct. Svelte has form for overloading JavaScript syntax with its own additions. This rune is not JavaScript. What it actually is is a flag for the compiler to abstract away the complexity of signals by saying "treat this value as reactive". When it's compiled, it generates all the signals needed to make the value reactive. But the ergonomics of using it are as mostly the same as if you were creating a value. It's not the same though, and so there are warnings in case you use it in a way that the compiler won't handle correctly.
- jakelazaroff 2y agoOh, weird, I could swear I've done that before. Especially weird because a class field is essentially the same thing.