1

I'm coding a simple JavaScript currency converter. Pulled the currency data from an API and stored it to a state object. Next, I wanted to add currency name, country and symbol to the app so I'm pulling that data from a Rest Countries API and storing it to "currencies" array.

Here's the code:

export const state = {
  date: [],
  time: {},
  currency: [],
  rates: {},
  result: [],
};

export const getSymbolsCountry = async function (symbol) {
  try {
    const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`);
    const json = await data.json();
    addInfoToSymbol(json[0]);
  } catch (err) {
    console.log(err);
  }
};

function addInfoToSymbol(data) {
  let country = {
    code: data.currencies[0].code,
    symbol: data.currencies[0].symbol,
    flag: data.flag,
    country: data.name,
  };

  state.currency.push(country);
}

Console logging the currency from state shows that it's an array but using map or forEach on it does nothing. console log state.currency Could someone please help me understand what I'm doing wrong cause I can't wrap my head around it.

1 Answer 1

0

What do you mean by using map of forEach on it does nothing ?

Here is an example where I use forEach on state.currency and its working perfectly.

const state = {
  currency: []
};

const getSymbolsCountry = async function (symbol) {
  try {
    const data = await fetch(`https://restcountries.eu/rest/v2/currency/${symbol}`);
    const json = await data.json();
    addInfoToSymbol(json[0]);
  } catch (err) {
    console.log(err);
  }
};

function addInfoToSymbol(data) {
  let country = {
    code: data.currencies[0].code,
    symbol: data.currencies[0].symbol,
    flag: data.flag,
    country: data.name,
  };

  state.currency.push(country);
}

Promise.all([
  getSymbolsCountry("EUR"),
  getSymbolsCountry("USD"),
  getSymbolsCountry("JPY")
])
.then(() =>
  state.currency.forEach(({code}) => 
    $("#result").append("<li>" + code + "</li>")
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="result"></ul>

1
  • Well, I'm passing state.curency crom the controller to the view class and it's show method and i don't get anything in the console log: show(val) { val.forEach(cur => console.log(cur)); } Mar 21, 2021 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.