I am pretty new to svelte started it a week ago......😁
I am trying to know about it i really loved❤️❤️ it but I have a problem☹️☹️
I am trying to access a $: variable in the script tags but i get an Error Cannot access 'greeting' before initialization
.
<script>
let name = 'world';
$: greeting = `Hello ${name}`
console.log(greeting)
</script>
<h1>Hello {name}!</h1>
I also tried declaring the variable with let prior to using it
let greeting
But in this case console.log
outputs undefined
.
The solution to your problem is to make the console.log(greeting)
statement reactive as well:
<script>
let name = 'world';
$: greeting = `Hello ${name}`
$: console.log(greeting)
</script>
<h1>Hello {name}!</h1>
Because console.log
is not a reactive statement in your example, it is actually executed before any reactive statement, following the 'normal' flow execution of your script. So when it is executed greeting
has not yet been set (your first error) or it has been set to undefined
through the let greeting
declaration (your second error).
By making console.log
reactive, you ensure it will be executed (a) after greeting
has been set (which solves your first issue), and (b) every time greeting
is set (which solves your second issue). And you do not have to declare greeting
prior to assigning it a value in a reactive statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With