Search code examples
javascriptsveltesvelte-3

Dispatched function called outside component initialization


I'm learning svelte 3 from this great tutorial. So I created a tab component like:

<script>
  import { createEventDispatcher } from "svelte";
  const dispatch = createEventDispatcher;
  export let items;
  export let activeItem;
</script>

<ul class="tab tab-block">
  {#each items as item}
    <li on:click={() => dispatch("tabChange", item)}>
      <div class:active={item === activeItem}>
        {item}
      </div>
    </li>
  {/each}
</ul>

And I imported it into the parent component Projects.svelte:

<script>
import Tabs from "./Tabs.svelte";
  let items = ["Projects", "Users"];
  let activeItem = "Projects";
//...
  const tabChange = (e) => {
    activeItem = e.detail;
  };
</script>

<Tabs {activeItem} {items} on:tabChange={tabChange} />

I see that svelte is compiled without errors and active and non-active tabs are rendered fine.. However, when I click a tab I get this error:

index.mjs:938 Uncaught Error: Function called outside component initialization
    at get_current_component (index.mjs:938)
    at createEventDispatcher (index.mjs:954)
    at Array.click_handler (Tabs.svelte:10)
    at HTMLLIElement.click_handler (Tabs.svelte:12)

I'm wondering what could be wrong and how can I fix it?


Solution

  • You forgot to call createEventDispatcher:

    <script>
      import { createEventDispatcher } from "svelte";
      const dispatch = createEventDispatcher(); // <-- () was missing
      // ..
    </script>
    
    ...