Svelte Error – Cannot access ‘variable_name’ before initialization

Total
0
Shares

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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like