Search code examples
angularionic-frameworkinappbrowserionic4ionic-storage

How to clear the ionic storage before submitting the new data


I'm creating an ionic app with a webapp inside inappbrowser. I made a separate ionic login form that sends the credentials to the webapp's login form so that I can login in the webapp.

Here's the flow of my current code:

If the user has a saved credentials in the storage, open webapp and automatically login the user; else, stay on the login page.

But the problem is, if I clear the storage every time the user has a new login, it returns a null value.

Also, I'm not very sure if my code is a good practice, what's the other way for this?

userInput: string = "";
passInput: string = "";
userKey:string = 'username';
passKey:string = 'password';

constructor(
  private platform: Platform,
  private iab: InAppBrowser,
  private storage: Storage
) { this.init(); }

init() {
  let promiseList = [];

  Promise.all([
    this.storage.get(this.userKey).then((username) => {
      console.log('Retrieved username is', username);
      promiseList.push(username)
    }),
    this.storage.get(this.passKey).then((password) => {
      console.log('Retrieved password is', password);
      promiseList.push(password)
    })
  ]).then(() => {
    console.log('promiseList', promiseList)
    if (validated) { this.openWebApp(promiseList) }
    else { //remain in the login page }
  })
}

login() {
  // this.storage.clear()
  this.storage.set(this.userKey, this.userInput)
  this.storage.set(this.passKey, this.passInput)
  this.init();
}

openWebApp(credentials) {
  console.log('credentials', credentials, credentials[0], credentials[1])
  this.platform.ready().then(() => {
    const browser = this.iab.create('https://www.mywebapp.com/login', '_blank', {location:'no', footer:'no', zoom:'no', usewkwebview:'yes', toolbar:'no'});

    browser.on('loadstop').subscribe(event => {
    browser.show();

    browser.executeScript({
        code: `document.getElementById("usernameInput").value=${credentials[0]} document.getElementById("passwordInput").value=${credentials[1]} document.getElementById("submitBtn").click()`
    })
  });
});

Here's what I want to achieve:

If the user logs in again with a new credential, clear the old one and save the new one.


Solution

  • Ionic Storage functions usually return Promises... So you need to wait these Promises to resolve before doing other stuff... For example:

    async login() {
      await this.storage.clear();
      await this.storage.set(this.userKey, this.userInput);
      await this.storage.set(this.passKey, this.passInput);
      this.init();
    }