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: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 executedgreeting
has not yet been set (your first error) or it has been set toundefined
through thelet greeting
declaration (your second error).By making
console.log
reactive, you ensure it will be executed (a) aftergreeting
has been set (which solves your first issue), and (b) every timegreeting
is set (which solves your second issue). And you do not have to declaregreeting
prior to assigning it a value in a reactive statement.