Async fetch and trouble a copy array in class

I have a problem… thant’s a code:

class Currency {
    cosnstructor() {
        this.currencyInfo = [];
    }

    getCurrency(getInfo) {
        this.currencyInfo = getInfo;
    }    
}

const actuallyCurrency = new Currency;

(async () => {
    const response = await fetch(`http://api.nbp.pl/api/exchangerates/tables/A`);
        const data = await response.json();
        const currency = data[0].rates; 
        currency.map(element => curArr.push(element));
})();

const curArr = [];

actuallyCurrency.getCurrency(curArr);

this code working good, but I need in this.currencyInfo a new array, not reference to array curArr.

>Solution :

There are a few improvements to be made. Probably the most important is arranging to check the currencyInfo instance variable after the fetch completes. This and other suggestions indicated by comments…

class Currency {
  cosnstructor() {
    this.currencyInfo = [];
  }

  // methods that assign (and don't return anything) ought to be called "set" something
  setCurrency(array) {
    this.currencyInfo = array;  
  }

  // it probably makes sense to have this class do it's own async initialization
  async fetchCurrency() {
    const url = `http://api.nbp.pl/api/exchangerates/tables/A`;
    // try/catch, so we can respond to failures
    try {
      const response = await fetch(url);
      const data = await response.json();
      // no need to map and not sure why the array needs to be copied. I suspect
      // it doesn't but [...array] copies array
      this.setCurrency([...data[0].rates]);
    } catch (error) {
      console.log('error fetching', error);
    }
  }   
}

// instantiation requires ()
const actuallyCurrency = new Currency();

// no async/await at the top level
actuallyCurrency.fetchCurrency().then(() => {
  console.log(actuallyCurrency.currencyInfo);
})

Leave a Reply