Check out this cool animation block for Svelte. I’m fetching something from a random remote API as shown below. Notice that you need to chain two Promises using then
to get the JSON response:
loading = fetch("http://localhost:3000/products").
then(response => response.json());
Then I will use the loading Promise with an async block:
{#await loading}
<div class="spinner-border" role="status">
<span class="sr-only"></span>
</div>
{:then results}
<div transition:fade>
// display the result somehow
</div>
{:catch error}
<p style="color: red">
{error.message} // show an error
</p>
{/await}
What I’m doing is showing the loading animation until the result comes in, then I use fading animation to show the result. I’m also using catch to display error for the worst-case scenario.
That’s it! If there is a better way to do this please let me know in the comments section.