This content originally appeared on CodeSource.io and was authored 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.
The post onMount Lifecycle In Svelte – Code example appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Jatin Hemnani
Jatin Hemnani | Sciencx (2021-02-19T11:06:26+00:00) onMount Lifecycle In Svelte – Code example. Retrieved from https://www.scien.cx/2021/02/19/onmount-lifecycle-in-svelte-code-example/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.