Home > Software design >  Async fetch and trouble a copy array in class
Async fetch and trouble a copy array in class

Time:11-10

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.

CodePudding user response:

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);
})

CodePudding user response:

and next trouble... a was tryed:

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

and i was tryed your ideas, but I still have empty my array in constructor

img

CodePudding user response:

I this this is what you want:

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

    getCurrency(getInfo) {
        this.currencyInfo = [...getInfo]; // <-- change this line
    }    
}

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);

... is an operator that does a shallow copy of it's argument. So using as above you'll get a new array in currencyInfo.

  • Related