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

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years 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.

egghead
egghead
~ just now

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today