How to check if key exists in local-storage


#1

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…


How to check if duplicate key exists in local -storage in ionic
#2

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.


#3
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


#4

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).


#5

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
			{
}