sveltesveltekit

Should I access the api directly inside the script tag in a svelte SPA?


I am writing a Svelte CSR application. I am wondering whether this is ok:

<script>
    const data = api.getDataAsync()
<script>

{#await data}
   <span>Loading</span>
{:then data}
   //display data
{/await}

If not why? should I do it the react way

<script>   
   let data = $state(undefined)
   onMount(()=>{
       api.getDataSync().then(apiData=>data=apiData)
   })
</script>
{#if !data}
   <span>loading...</span>
{:else}
   //display data
{/if}

Edit: Because I am using PocketBase, I have SSR turned off.


Solution

  • Neither, in SvelteKit use a load function.

    This is the standard mechanism for loading data which hooks into other mechanisms, including navigation where data can be pre-loaded on link hover or tap and a page is only shown when the data is loaded.

    (If the load is known to take longer you can return a promise and #await that on the page, but for data that load quickly, only showing the page once it is done gives a better experience without any layout shifts.)