Ionic, Edit and save

#1

Hi there, i want to edit the data that is stored in database and after editing i want to save or update the data, but my current code is creating another data base and removing the last saved database.
main.ts

 Items = [];
edit(name, address){
    let addModal = this.modalCtrl.create(Edit, {
      Edit:name,address
    });

    addModal.onDidDismiss((Item) => {
      if(Item){
        this.save(Item);
      }
    });
 addModal.present();
  }
  save(Item){
    this.Items.push(Item);
    this.dataService.save(this.Items);
  }

edit.ts

ionViewDidLoad() {
    this.name= this.navParams.get('name');
    this.address= this.navParams.get('address');
  }

  save(){
    let Item= {
      name: this.name,
      address: this.address,
    };
    this.view.dismiss(Item);
  }

any Help!!!

#2

I don’t see any ‘database’ alterations here. Care to provide the code where you actually store and fetch information?

#3

data.ts

import { Storage } from '@ionic/storage';
import { Injectable } from '@angular/core';
 
@Injectable()
export class Data{
 
  constructor(public storage: Storage){
 
  }
 
  getData() {
    return this.storage.get('Data');  
  }
  save(Items){
    let newData = JSON.stringify(Items);
    this.storage.set('Data', newData);
  }
}
#4

No need to stringify if you’re using ionic storage. You should just set the items instead.

1 Like
#5

Okay, Thank you will look on that too. but m creating a database in home.ts too and i want to update that data.

#6

I understand, but probably it creates a new instance everytime because you stringify it. How does your indexeddb look like in chrome dev tools?

#7

0 “eventData” “[{“eventName”:“taimoor”,“eventLocation”:“sadasdasdsa”,“eventDescription”:“qwqweqeqweqweqwe”}]”

#8

Done that, but still stuck on that.

#9

Could you answer that one? And could you also show where you actually call getData()?

#10

here’s the function in,
data.ts

getData() {
		return this.storage.get('eventData');  
	}

and here it is called in main.ts

constructor(public navCtrl: NavController, public modalCtrl: ModalController, public dataService: Data) {
    this.dataService.getData().then((eventData) => {

      if(eventData){
        this.Items = JSON.parse(eventData); 
      }
    });
  }
#11

:slight_smile: found a solution, thanks for you help. and solution was i have to just change 1 line in edit function in main.ts

edit(name, address){
   let index = this.Items.indexOf(Item);
    let addModal = this.modalCtrl.create(Edit, {
      Edit:name,address
    });

    addModal.onDidDismiss((Item) => {
     if(index > -1){
         this.Items[index] = Item;
          this.dataService.save(this.Items);
      }
    });
 addModal.present();
  }

this will save the data on that index. Hope this will help. :grin: