DEV Community

Cover image for How onMount() works in Svelte?
Ashutosh
Ashutosh

Posted on

How onMount() works in Svelte?

Often, a series of actions requires to perform when a component renders to DOM. For example, we need to call a function before updating or removing a component. To handle this, Svelte has built-in lifecycle methods like **onMount(), beforeUpdate, afterUpdate, onDestroy()**.

In this article, we learn about the onMount() lifecycle method of svelte. If you are a beginner, you must visit my old posts on Svelte.

Svelte creates, mounts, updates, and destroys a component. In short, every component has a lifecycle. The application makes and eventually destroys a svelte component.

The onMount() method executes after the component renders to the DOM.

Create a new file OnMountComponent.svelte, And add the following content

<script>
    import { onMount } from 'svelte'

    let tasks = []
    const url = 'https://jsonplaceholder.typicode.com/todos/'

    onMount( async () => {
        fetch(url)
            .then( response => response.json() )
            .then( data => { tasks = data } )
    });
</script>

<table>
    <thead>
        <tr>
            <th>Task Id</th>
            <th>Task Name</th>
            <th>Status</th>
        </tr>
    </thead>

    {#each tasks as t}
        <tr>
            <td>{t.id}</td>
            <td>{t.title}</td>
            <td>{t.completed}</td>
        </tr>
    {/each}
</table>
Enter fullscreen mode Exit fullscreen mode

We imported an onMount() function and we use a public url https://jsonplaceholder.typicode.com/todos/ to fetch the API. This is a public API for testing purpose, please do not abuse it.

Here we use an onMount() to get the data using the fetch API.

onMount( async () => {
        fetch(url)
            .then( response => response.json() )
            .then( data => { tasks = data } )
    });
Enter fullscreen mode Exit fullscreen mode

We'll discuss fetch API in different article.

Next is to import this component in the App.svelte.

<script>
    import OnMountComponent from "./OnMountComponent.svelte";
</script>

<main>
    <OnMountComponent />
</main>

<style>
    main {
        text-align: center;
        padding: 1em;
        max-width: 240px;
        margin: 0 auto;
    }

    @media (min-width: 640px) {
        main {
            max-width: none;
        }
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Thats all for now. In this article, we learn how to the use onMount() function in Svelte to load the component in DOM. See you in the next article.

Discussion (0)