Use an onMount lifecycle method to fetch and render data in Svelte 3

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Every Svelte component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.

The one you'll use most frequently is onMount, which runs after the component is first rendered to the DOM.

In this lesson we're going to learn how to use onMount to fetch and render data from Star Wars API.

Instructor: [0:00] We would like to use the Star Wars API to fetch the data of our Star Wars characters. We would like to display this data using this each loop over here.

[0:07] Currently, we're displaying only loading over here because the characters aura is currently empty. In order to fetch this data, we're going to import onmount from salt. Onmount basically triggers whenever a component is being mounted to the dome.

[0:20] We're going to use this onmount like this. I'm going to create an async function. This function is going to fetch the API response from the Star Wars API. I'm going to do fetch from Star Wars API/people.

[0:33] Next up, I'm going to get the JSON response from this API. From this response, I'm going to get the character's data and store it within the character's array. Now, if I save in the first dot, we're going to see the desired effect.

[0:46] In this list, we have the searcher and the name, the height, and the birth here of each Star Wars character. We are displaying those over here.

[0:53] Important thing to know about the onmount is that whenever a function passed in as an argument is going to return another function, this function is going to actually get called whenever the component is being destroyed.