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
Your async function will return a Promise. You should handle its result with a callback.
Like this:
There is native syntax (with many variants) for awaiting promises in markup:
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}
: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 thedata
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 theAccept-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.