search

Home  >  Q&A  >  body text

Access the return value of an asynchronous function using Svelte components

<p>I have the following code snippet (layout.svelte): </p> <pre class="brush:js;toolbar:false;">import { getLang } from "$lib/locale"; import { browser } from "$app/environment"; const loadLang = async () => { if (browser) { // return await getLang(document.documentElement.lang, "home").then( function (data: any) { // const nav = JSON.stringify(data.nav); // console.log(nav) // return nav; // }); const initLocale= await getLang(document.documentElement.lang, "home"); return initLocale.json(); } }; const a = loadLang(); console.log(a); </pre> <p>The purpose of this code is to detect the browser language and the route of the request, and then search for the correct JSON file corresponding to the language and page. But there is a problem, I cannot access the language data of the async <code>loadLang()</code> in order to use it in the HTML element of the component, except in many answers mentioned here (which is not what I'm looking for) , what I want is a way to access the return value of the above function and use it in an HTML element? </p>
P粉463824410P粉463824410477 days ago558

reply all(1)I'll reply

  • P粉174151913

    P粉1741519132023-08-16 18:17:53

    In markup, there is native syntax (with many variations) that can be used to await promises:

    {#await loadLang() then lang}
      <span>{lang.someValue}</span>
    {/await}
    

    Another option is to declare a variable in the top scope and set it after the data is loaded. Of course it will be undefined at first, or whatever other value you initialize it to. Then usually combined with {#if}:

    let lang;
    loadLang().then(l => lang = l);
    
    {#if lang}
      <span>{lang.someValue}</span>
    {/if}
    

    Having a guard on browser is not good. You may want to move the data loading into the layoutloading function so that it can be passed as a data attribute and can be used during SSR and CSR, and for Available on every page using layout.

    Do not use document.documentElement.lang, instead use the Accept-Language header of the request on the server.

    Loading data before the page is served/rendered also prevents potential layout changes or loading indicators.

    reply
    0
  • Cancelreply