TaGi Asadullazadeh
TaGi Asadullazadeh

Reputation: 91

Update array value inside promise ionic 4

I want to get API data and set to localStorage(after convert image from the server to base64). When I get data from API, I create a simple loop for update image URL to base64 format but this.users[key].picture["large"] = dataUrl; don’t work. Because of dataUrl value don’t work outside of a function. How can I update the row object? What can I do?

this.http.get<User[]>('https://randomuser.me/api?result=100').subscribe(data => {
  this.users = data['results'];

  for (let key in this.users) {
    let value = this.users[key].picture["large"];

    this.toDataURL('//cors-anywhere.herokuapp.com/' + value)
      .then((dataUrl) => {
        console.log(dataUrl);//correct returned value
        this.users[key].picture["large"] = dataUrl;
      });
        console.log(this.users[key].picture["large"]);//not equal to dataUrl
  }

  this.storage.set('users', "");//clear
  this.storage.set('users', this.users);
  console.log(this.users);
});

my toDataUrl function:

public toDataURL(url) {
return fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  }));

}

Upvotes: 1

Views: 868

Answers (1)

Sergey Rudenko
Sergey Rudenko

Reputation: 9227

You need to call storage and persist data inside async response:

this.http.get<User[]>('https://randomuser.me/api?result=100').subscribe(data => {
  this.users = data['results'];

  for (let key in this.users) {
    let value = this.users[key].picture["large"];

    this.toDataURL('//cors-anywhere.herokuapp.com/' + value)
      .then((dataUrl) => {
        console.log(dataUrl);//correct returned value
        this.users[key].picture["large"] = dataUrl;
        this.storage.set('users', this.users);
  console.log(this.users);
      });
  }
});

Also do not do “set” “” to clear storage. Storage set method will override whatever other value you had there so there is no need to clear it this way

Upvotes: 1

Related Questions