Home > database >  Updating a data inserts a new data into the firebase realtime database
Updating a data inserts a new data into the firebase realtime database

Time:12-01

I used the update() function for my code, but it keeps adding a new entry instead of editing the data I want to edit.

UpdateData1.addEventListener('click', (e) => {
  e.preventDefault();
  var updateCrop = document.getElementById('updateCrop').value;
  var updateDescriptionCrop = document.getElementById('updateDescriptionCrop').value;

  if (document.getElementById('updateCrop').value == '' || document.getElementById('updateDescriptionCrop').value == '') {
    alert("Fields should not be empty");
  } else {

    update(ref(database, "Crops/"   updateDescriptionCrop), {
        Crops: updateCrop,
        CropInfo: updateDescriptionCrop
      })
      .then(() => {
        alert("Crop information successfully updated");

      })
      .catch((error) => {
        const errorMessage = error.message;
        // ..
        alert(errorMessage);
      });

  }

});

CodePudding user response:

Let's assume that updateDescriptionCrop is your key.

In order to update the entity in db you should do this:

update(ref(database), {
  ["/Crops/"   updateDescriptionCrop]: {
    Crops: updateCrop,
    CropInfo: updateDescriptionCrop
  }
}).then(() => {
  alert("Crop information successfully updated");
}).catch((error) => {
  const errorMessage = error.message;
  alert(errorMessage);
});

Read more here.

Update:

Generate random UUID when you're creating your entries as the key of your entries using uuid library:

const { v4: uuidv4 } = require('uuid');
function writeData(crops, cropDescription) {
  const entryId = uuidv4();
  set(ref(db, 'Crops/'   entryId), {
    Id: entryId,
    Crops: crops,
    CropInfo: cropDescription
  });
}

And then when you want to update your entry, use this id:

update(ref(database), {
  ["/Crops/"   cropId]: {
    Id: cropId,
    Crops: updateCrop,
    CropInfo: updateDescriptionCrop
  }
}).then(() => {
  alert("Crop information successfully updated");
}).catch((error) => {
  const errorMessage = error.message;
  alert(errorMessage);
});
  • Related