Svelte throws error, “Cannot access variable_name before initialization” when a reactive variable is used in non-reactive variable. According to Svelte documentation

Reactive statements run immediately before the component updates, whenever the values that they depend on have changed.

So, reactive variables get their values before component update and are uninitialized when a local variable requires them. The below code will throw error –

<script>
  let superHero = ["Ironman", "Captain America", "Spiderman"];

  $: reactiveSuperHero = superHero;

  let thisUsesReactive = reactiveSuperHero.filter(d => {
    if (d.indexOf("man") > -1) return true;
    return false;
  });
</script>

<main>
  <h4>All superhero = {reactiveSuperHero}</h4>
  <h4>Superhero with man = {thisUsesReactive}</h4>
	<button on:click={() => {superHero = [...superHero, "Superman"]}}>Add Superman</button>
</main>

This is because filter is used on reactiveSuperHero which will be undefined as its value will only be initialized before component update.

To solve this error we need to make thisUsesReactive variable reactive too using $:.

So, this code will not throw error –

<script>
  let superHero = ["Ironman", "Captain America", "Spiderman"];

  $: reactiveSuperHero = superHero;

  $: thisUsesReactive = reactiveSuperHero.filter(d => {
    if (d.indexOf("man") > -1) return true;
    return false;
  });
</script>

<main>
  <h4>All superhero = {reactiveSuperHero}</h4>
  <h4>Superhero with man = {thisUsesReactive}</h4>
	<button on:click={() => {superHero = [...superHero, "Superman"]}}>Add Superman</button>
</main>

    Tweet this to help others

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles