3 ms·
I can’t do this: const createCounter = () => $state(0); let counter = createCounter(); > $state(...) can only be used as a variable declaration initialize
by tobr 2y ago
I 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.