concept onMount in category svelte

appears as: onMount
Svelte and Sapper in Action

This is an excerpt from Manning's book Svelte and Sapper in Action.

<script context="module">
  export function add(n1, n2) {
    return n1 + n2;
  }
</script>
 
<script>
  <!-- Component JavaScript goes here. -->
</script>

<!-- Component HTML goes here. -->

<style>
  /* Component CSS goes here. */
</style>
<script>
  import Demo from './Demo.svelte';
  let show = false;                      #1
</script>

<label>
  <input type="checkbox" bind:checked={show}>
  Show
</label>
{#if show}
  <Demo />
{/if}

The lifecycle functions can be called any number of times. For example, if onMount is called three times, passing it three functions, all of them will be called when the component is mounted, in the order in which they were registered.

Note that functions passed to beforeUpdate are called before functions passed to onMount. This happens because component props and state are evaluated before a component is added to the DOM.

Here is an example that retrieves data about employees at a company from an API service when the component is mounted. This is the same API service described in section 4.3. The array of employee objects returned is sorted by their names (first name before last name) and stored in a top-level variable. The component renders the employee data in a table (see figure 8.1).

Figure 8.1 Employee table

Listing 8.3 App that uses onMount to fetch data