Search code examples
javascriptangularionic-frameworkionic2dom-events

Ionic run function once only (on first time app is run)


I am trying to execute a function which sets an array to default values in ionic storage, however I need this to happen only when the app is run for the first time(after it is installed on a users phone). Currently is it firing every time the app is launched as I have the function in my component.ts --> platform.ready(). This is my function, I am just not sure where to place it. As you can see I am setting the array to default values, this array gets updated in other sections of the app. When the user closes the app and reopens it, the array is getting reset to the default values, hence I need to make the function run once only i.e. when the user runs the app for the first time.

  let array = [];
  array.push(
    { "username":"Name & Surname*", "email":"Email*", "cellnumber":"Cell Number*", "displayname":"Displayname*", "profilepicture":"urlpath", "projectname":"Projectname", "dateadded":"Dateadded", "notes":"Notes", "image":"Image", "taskname":"Taskname", "taskdescription":"Taskdescription", "taskimage":"Taskimage" }
  );
  this.storage.set('myStore', array); 

Thank you


Solution

  • Check if the 'myStore' key is set in Storage:

    this.storage.get('myStore').then(data => {
       if ( !data ) {
           let array = [];
           array.push(yourDataObject);
           this.storage.set('myStore', array); 
       }
    })
    .catch(err=>{
       console.log('Your data don't exist and returns error in catch: ' + JSON.stringify(err);
    });
    

    Haven't tested this code, but it should work.