onMount Lifecycle In Svelte – Code example
Posted on: February 19, 2021 by Jatin Hemnani
What Is Lifecycle?
Every component has a Lifecycle that starts when it is created. Sometimes we need a function to run when the component is rendered like fetching APIs.
Import onMount
<script>
import { onMount } from 'svelte';
let todos=[];
</script>
Here we have imported the onMount lifecycle and created an empty array.
Using onMount
onMount(async()=>{
let response=await fetch('https://jsonplaceholder.typicode.com/todos/')
todos=await response.json()
})
Above we have fetched the API and assigned it to todos array.
Rendering In The DOM
{#each todos as todo}
{todo.title}
{/each}
Now we have rendered the todos array with each block provided by Svelte.
Share on social media
//