Svelte – 2 ways to load asynchronously

An example of two ways to load asynchronously on a page with reactive framework Svelte

1. Using the await and then blocks

We receive data from the backend in the usual way, for example:

let settings = getFetchOther(‘settings / get-user-timers /’);

When displaying html, we put the constructions:

{#await settings}
{: then settings }
{/ await}

Looks like that:

<div class=“table”>
<div class=“body”>
{#await settings}
{: then settings }
{#each settings as setting}
<div class=“item”>
<div class=“cell title”>{setting.title}</ div>
<div class=“cell percent”>{setting.percent}</ div>
</ div>
{/ each}
{/ await}
</ div>
</ div>

2. Using onMount

Load using the module onMount in svelte

import {onMount} from “svelte”;

let settings = [];

onMount(async () => {
getFetchOther(‘settings / get-user-timers /’)then(function (res) {
settings = res
});
});

And then you can do without await block in html:

<div class=“table”>
<div class=“body”>
{#each settings as setting}
<div class=“item”>
<div class=“cell title”>{setting.title}</ div>
<div class=“cell percent”>{setting.percent}</ div>
</ div>
{/ each}
</ div>
</ div>

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *