0

I am trying to fetch the exchange rate of one currency so that I can use it in my conversion.

currenycodes = new Array("USD", "EUR", "INR", "JPY", "RUB", "GBP", "CAD", "MXN", "CNY", "KRW", "BTC", "ETH");

This is the codes array from which I find the code which the user wants as the base (the user enters the code and I find its index in the array).

var sourcecode = currenycodes[sourceIndex];
var targetcode = currenycodes[targetIndex];

After I find the codes the user wants to exchange between (supposed USD to EUR). I feed these codes to the API.

var url = `https://v6.exchangerate-api.com/v6/c698605f2b9ef5f1ef716047/latest/${sourcecode}`;

    async function currency() {
            let res = await fetch(url);
            let data = await res.json();
            let val=data.conversion_rates.targetcode;
            console.log(val)
        // console.log(data.conversion_rates.EUR);
    }

Here conversion* rate is an array of key:value pairs e.g.: {USD: 1, AED: 3.6725, AFN: 85.8224, ALL: 97.9119*}

I need that value for the further conversion process, but I am getting undefined for some reason where the good data.conversion_rates.EUR gives perfect value.

Any help would be greatly appreciated, I can't do this alone.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zethyst
  • 33
  • 6
  • @Daedalus I was taught await doesn't work unless the function is async – Zethyst Jun 22 '23 at 21:28
  • @Daedalus direct call just below, eg: currency() – Zethyst Jun 22 '23 at 21:29
  • @Daedalus no bro, is there any chance the problem is with variable 'targetcode' which is a string I am trying to attach to a response's data? – Zethyst Jun 22 '23 at 21:33
  • 1
    `I need that value for the further conversion process, but I am getting undefined for some reason where the good data.conversion_rates.EUR gives perfect value.`: This is IMHO a duplicate to [Accessing an object property with a dynamically-computed name](https://stackoverflow.com/questions/4244896/accessing-an-object-property-with-a-dynamically-computed-name): `let val=data.conversion_rates[targetcode]`. If you agree with that @Zethyst I'll close it as duplicate. – t.niese Jun 22 '23 at 21:36
  • @t.niese I missed that; I'm going to retract. – Daedalus Jun 22 '23 at 21:39
  • @Daedalus THANKS!! data.conversion_rates[targetcode] worked just fine. – Zethyst Jun 22 '23 at 21:40
  • @Zethyst Thank t.niese; not me. I went off the wrong track. – Daedalus Jun 22 '23 at 21:47
  • @t.niese THANKSSS MAN. Because of you, my project got completed! https://scalemate.vercel.app/ – Zethyst Jun 22 '23 at 23:20

0 Answers0