devjavascriptsveltesveltekitasync
(updated ) ~2 min (331 words)

Sveltekit: Process dynamic data with svelte and sveltekit

Svelte Logo with arrow in the background depicting dynamic content loading

Using sveltekit if you have used svelte before is quite straightforward. At least most of the time.
Loading and displaying dynamic (as in by API call) wasn't that obvious to me at first.
So here's a short description of the most important things to keep in mind.


Sveltekit Routes

First of all, sveltekit allows you to use dynamic endpoints by just using the right filenames.

I.e. using routes/test/[message].svelte enables you to replace [message] with whatever parameter you want. Transform the parameters into props

Transform the parameters into props

By adding the following module to your .svelte file you kind of publish the parameters to your frontend.

<script context="module">
    export async function load(context) {
    let year = context.page.params.message;
    return { props: { message }}
}
</script>

Also, you should add the following prop export to your svelte <script> notation:

export let message;

Now you can use it within the markup part:

<div>Your message: {message}</div>



Handle Dynamic data

Another thing is handling dynamic content you got from an API call like this:

let text = getText();
async function getText() {
    return await fetch('http://localhost:5000/api/text)
        .then(r => r.json())
        .then(data => {
            return data.text;
        });
}

This is similar to svelte's onMount function but that didn't work for me using the following async markup functions.

{#await text}
    <div>loading...</div>
{:then text}
    <div>The text: {text}</div>
{:catch error}
    <div><p style="color: red">{error.message}</p></div>
{/await}

Svelte is able to handle asynchronous content loading via the {#await} function very well.

Basically, this is like using the await syntax via javascript but within the markup.

So you don't have to care about the async logic and svelte will give you the output as soon as the request was completed.

It can even handle errors and is race condition save.

That's it from me this month.