skip to Main Content

I have the following piece of code (+layout.svelte):

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);

What this snippet does is detect the browser language, the route requested and then searches for the correct JSON file corresponding to the language and the page. But there is a problem, I am unable access the language data of the async loadLang() to use it in the component’s HTML elements and there is no way for me to actually do that other than what many answers here stated (which is not what i’m looking for), What I want is a way to access the returned value of the aforementioned function and use it in the HTML elements?

2

Answers


  1. Your async function will return a Promise. You should handle its result with a callback.

    Like this:

    loadLang().then(result => {
      // and here do whatever you want with the result, log it for example
      console.log(result);
    })
    
    Login or Signup to reply.
  2. There is native syntax (with many variants) for awaiting promises in markup:

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

    The other alternative would be to declare a variable in the top level scope and set after the data is loaded. Of course it will be undefined or whatever else you initialize it to, first. This then usually would be combined with {#if}:

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

    Having a guard on browser there is not great. You might want to move the loading of the data to a +layout load function, so it is passed as the data prop and can be used during SSR and CSR and is available to every page using the layout.

    Instead of using document.documentElement.lang use the Accept-Language header of the request on the server.

    Loading the data before the page is served/rendered also would prevent potential layout shifts or loading indicators.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search