Access the return value of an asynchronous function using Svelte components
P粉463824410
P粉463824410 2023-08-16 00:11:05
0
1
500
<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粉463824410
P粉463824410

reply all(1)
P粉174151913

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!