i want to create alert if user wants to create same name account again if the account is already there in local storage.how can we do this in ionic.
If I am not putting any alert message their,then the new value get replaced by the previous one,but I want that alert message should be generated if the value is being replaced also…
You first check if you can get
the key for the name, if yes you output the error message, otherwise you set
it. You will probably have an array set as accounts
in local storage, so you get that array, check if the name is already in that array, then you handle the cases.
let key = this.account.value.name;
key = this._formatString(key);
let entries = [];
let entry = new Entry(new Date().toString(), 'DEP','Opening Balance','R',0, this.account.value.balance, this.account.value.balance);
// console.log(entry);
entries.push(entry);
console.log(JSON.parse(localStorage.getItem(key)));
let checkbook = new Checkbook(this.account.value.balance, this.account.value.budget, entries);
var cart = localStorage.getItem(key) || {};
if (cart) {
console.log(JSON.parse(localStorage.getItem(key)));
alert("Account exists");
}
else{
this.store.set(key, JSON.stringify(checkbook)).then(val => {
this._presentToast("Successfully created account: "+this.account.value.name);
this.events.publish('account:created', new Date().toLocaleString());
this.navCtrl.pop();
});
}
I tried this in mt home.ts file,but everytime I am getting the message key exists…,
whether or not it is a duplicate…
Please tell where I am wrong
What is this? I think you should use Ionic Storage here. Then .get
returns a promise, so you have to work with it differently (see docs for example).
1 Like
this issue has been solved…
let key = this.account.value.name;
key = this._formatString(key);
this.store.get(key).then(data=>
{
if(data)
{
alert("exists");
}
else
{
}
4 Likes
And if data has boolean variable?
Doesn’t matter. You just check if the key in general exists.
try this
async keyAlreadyExist(_key): Promise<boolean> {
let st = false;
await Storage.keys()
.then((rsp) => {
const f = rsp.keys.find((element) => element === _key);
if (f === undefined || f === null) {
st = false;
} else {
st = true;
}
})
.catch((e) => {
console.error(e);
st= false;
});
return st;
};