response.json()) " /> response.json()) " /> response.json()) "/>

getter method does wait for a previous async call to complete

50 views Asked by At

I have this in my JS file :

let xe = 0;

const get_usd2inr = async () =>
{
    return await fetch(BASE_URL + "api/usd")
    .then(response => response.json())
    .then(response =>
    {
        return response;
    });
}

document.addEventListener("DOMContentLoaded", async () =>
{
    xe = await get_usd2inr();
});

Alpine.store('local_data',
{
    // ...

    get ri_total()
    {
        let usd2inr = xe.usd2inr;
        let total = parseFloat(250 * usd2inr).toFixed(2);        
        const formatedNumber = new Intl.NumberFormat('en-IN', { currency: 'INR' }).format(total);
        return formatedNumber;
    }
});

I have this in my HTML which probably gets called right after AlpineJS init and before DOMContentLoaded ?

<input
    type="text" id="ri-total"
    :value="$store.local_data['ri_total']"
    x-mask-x:dynamic="$money($input)"
    readonly    
/>

The above INPUT's value is NaN when I want it a number, even if it's 0.

1

There are 1 answers

5
Lajos Arpad On

You can default it to 0 via

return isNaN(formatedNumber) ? 0 : formatedNumber;

EDIT

If defaulting to another value, such as 20817 makes more sense, then you can use that as your default value instead of 0.

But relative currency values change over time, so it is up to you whether you have a better default than 0.

You will need to debug to see whether there are issues other than a lacking default, see what happens when you get valid values and if it defaults even then. Because if so, you might have a number formatting problem as well.