How onDestroy() lifecycle function works in Svelte?
When we removed the component from DOM, the onDestroy() method is used. We need to call it before the component is removed from the DOM.
Let's create a new component, DateAndTimeComponent.svelte
And add the following code.
<script>
import { onMount } from 'svelte'
let tasks = []
const url = 'http://time.jsontest.com'
onMount( async () => {
fetch(url)
.then( response => response.json() )
.then( data => { tasks = data } )
});
</script>
<table>
<thead>
<tr>
<th>Date</th>
<th>Epoch Time</th>
<th>Time</th>
</tr>
</thead>
<tr>
<td>{tasks.date}</td>
<td>{tasks.milliseconds_since_epoch}</td>
<td>{tasks.time}</td>
</tr>
</table>
We have only implemented theonMount()
lifecycle function. If you are not aware ofonMount
then please visit the followingarticle
.
And in the App.svelte
add the following:
<script>
import DateAndTimeComponent from "./DateAndTimeComponent.svelte";
let showComponent = false;
</script>
<main>
{#if showComponent}
<DateAndTimeComponent />
{/if}
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
If you visit the webpate http://localhost:5000
then you'll see an empty page because showComponent
variable is false at the moment.
Lets add a button
to show the component. onMount
will only be called once when the component is loaded to the DOM.
In the App.svelte
, add the following under the main
tag.
<script>
....
..
..
..
</script>
<main>
<button on:click={ () => showComponent = !showComponent }>Show Component</button>
{#if showComponent}
<DateAndTimeComponent />
{/if}
</main>
And in the DateAndTimeComponent.svelte
we'll add the onDestroy
lifecycle function.
<script>
import { onMount, onDestroy } from 'svelte'
let tasks = []
const url = 'http://time.jsontest.com'
onMount( async () => {
fetch(url)
.then( response => response.json() )
.then( data => { tasks = data } )
});
onDestroy( () => {
console.log("Date Component removed")
});
</script>
<table>
<thead>
<tr>
<th>Date</th>
<th>Epoch Time</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>{tasks.date}</td>
<td>{tasks.milliseconds_since_epoch}</td>
<td>{tasks.time}</td>
</tr>
</tbody>
</table>
Take a look at import { onMount, onDestroy } from 'svelte'
and
onDestroy( () => {
console.log("Date Component removed")
});
onDestory
is only called when the element is removed from the DOM. And thats it. It will work like the below gif.
AK Newsletter
Join the newsletter to receive the latest updates in your inbox.