Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Martin Coutts
Martin Coutts
18,154 Points

Value on input not updating quick enough

I am having a bit of an issue with a small part of a project. I have got all the difficult stuff working in requesting and parsing the correct data from an API however on the output to the user to update it on the DOM I need to double click the calculate button even though all the rest of the data is being updated on the first click.

Here is a link to my repo https://github.com/martincavaliers/myCurrencyConverter/tree/apiIntegrationJquery

Any help would be great as it is the last thing I need to fix.

2 Answers

Hey,

Since you are making an API call, then the call doesn't return the data fast enough in order to place the data to the DOM. You can fix the problem, if you first wait for the API call to finish and then place the value to DOM. Using the .this will do the trick. Hope this helps.

$(document).ready(function () {
    getCurrencyData("https://free.currencyconverterapi.com/api/v6/currencies", currencyJson);

    // Calculate Button Event Handler
    $('#calculateBtn').on('click', function(){
        currentCurrency = $('#currentCurrencyType').val();
        newCurrency = $('#newCurrencyType').val();
        currentAmount = $('#currentMoney').val();
        transferSelector = currentCurrency+'_'+newCurrency;
        // console.log(currentCurrency, newCurrency);

        $.get('https://free.currencyconverterapi.com/api/v6/convert?q='+transferSelector, function(data){
            $.each(data.results, function(index, option){
                transferRate = option.val;
                $('#transferRate').val(transferRate);
                newAmount = currentAmount * transferRate;
                return newAmount;
            });
        }).then(data => {
            $('#newValue').val(newAmount);
        })
    });

});
Martin Coutts
Martin Coutts
18,154 Points

That worked great. Thanks very much. So did you just chain the change of the #newValue select after the API call and that way the whole thing has to function together?

Basically yes. I used .then, which means that after the api call something will happen. This will ensure, that api loads before using the data returned from that in the dom.