Use await block to wait for a promise and handle loading state in Svelte 3

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

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Most web applications have to deal with asynchronous data at some point.

Svelte 3 apps are no different, luckily Svelte allows us to await the value of a promise directly in markup using await block.

In this lesson we're going to learn how to use the await block to fetch the data from a Star Wars API and both display the data and handle loading state.

Instructor: [00:00] We have a function which is using the Star Wars API in order to fetch our unknown Star Wars character. We would like to be able to use this function to display the character name over here. One way to do that would be to use this function. Then, whenever there is a response, assign the character variable to this response.

[00:18] Now we have to handle the loading state manually. With Svelte, there's a different solution to this problem. First, let me move that, and next, assign the promise return from this function to a variable which I'm going to call promise. I'm going to remove this character a bit. Command that for a second.

[00:33] Next, we would like to use the await block. Let me close that as well. Await block instead allows you to await for a promise to resolve and then display content inside of this block based on this promise. I'm going to await our promise. Whenever we have a response, I'm going assign it to a character variable. I'm going to use the h1 header to display this character's name.

[00:54] As we mentioned before, we would like to be able to handle this loading state. Right now, if I refresh this, while we are waiting for the server to respond, there's a blank space. In order to do that, we need to modify the await block in order to handle this loading state. I'm going to do when character. Whenever we have our character, we're going to display this character's name.

[01:11] If you are still waiting for the character, I'm going to display a header which is going to say, "loading." Now we have the desired effect. If you are still waiting for the response from the server, we have the loading text. Whenever there's a response, we are going to get the name of the Star Wars character.