Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading