Hi there
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 .ie. 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
Any help? I am still stuck with this.
Much taken out for brevity…
import { Storage } from '@ionic/storage';
export class MyApp {
constructor(
private storage: Storage
) {
platform.ready().then(() => {
updateFields().then(() => {
//DO WHATEVER
});
});
}
async updateFields() {
const storageName = 'myFields';
const currentKeys = await this.storage.keys();
if(!currentKeys.some(k => k === storageName)) {
const array: {}[] = [{ "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" }];
await this.storage.set(storageName, array);
}
}
}
2 Likes
found a solution, check data inside 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);
});
thanks I found a solution
Your version is worse. It’ll have to actually pull the data first which is more expensive. Mine does it based on looking up the the keys.
Also, you need more type safety.
1 Like
agreed, your answer is better, thank you