1

I'm stuck retrieving all values from capacitor storage on Ionic 5, I'm retrieving all the time ZoneAwarePromise or Array Iterator, how to deal with it?

Thank you

//MAIN.ts

ngOnInit() {    
    let vaya = this.storage.keys()
    .then(result => {
      return result
    });
    vaya.then(data => {
      for (let item of data) {
        console.log(this.storage.getItem(item))
      }
      
    })
  }

//SERVICE STORAGE.ts

async keys() {
    const { keys } = await Storage.keys();
    console.log('Got keys: ', keys);
    return keys
}

1 Answer 1

1

Capacitor Storage is asynchronous so to retrieve all the values it has you need to:

  1. Make sure Capacitor has initialized
  2. Obtain the keys
  3. Write a loop that can do async processing

This should work (this will retrieve data sequentially):

ngOnInit() {  
    let values = [];  
    this.storage.keys().then(async (keys) => {
      for (let key of keys) {
        let value = await this.storage.get(key)
        values.push(value)
      };
    });
  }

You can also make the promises run in parallel:

  ngOnInit() {  
    let values = [];  
    this.storage.keys().then(async (keys) => {
      const promises = keys.map(key => this.storage.get(key))
      values = await Promise.all(promises);
    });
  }
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you i did it, can you tell me how to see the result at the same moment? i have to refresh the page to see the changes
Also it would be nice if i can ordered them by id (1,2,3...)
hm can you elaborate? by see result you mean console or?
i meant in the app, when its already saved on the storage, in other tabs should appear the new one, but only appears when its refreshed the app(F5 on browser), oh sorry about the numbers, the key is :0,1,2,3 and the value is the text, then i just want to make sure it's ordered by numbers
nothing? i still need why i need to refresh it to see the new result
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.