Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase update field using variable in javascript

I have a function which should go ahead and update the database on firebase

function editUser() {
  var userID = document.getElementById('userID').value;
  var editUserField = document.getElementById('editUserField').value;
  var newUserValue = document.getElementById('newUserValue').value;

  var database = firebase.database().ref().child('users/' + userID);
  database.once("value", function(snapshot){
      console.log(snapshot.val());
  })

  database.update({
    editUserField: newUserValue
  })

}

The above code is sort of working. Its getting the correct user, but whats not happening is the field is not getting updated, but instead, its creating a new field in the database and assigning it the value.

Looks like a key pair value is getting passed in

editUserField: newUserValue

but its actually taking the value editUserField

rather than getting getting it from the input:

var editUserField = document.getElementById('editUserField').value;

The value is actually getting stored correct from:

var newUserValue = document.getElementById('newUserValue').value;

But it doesnot update the value for the correct key, instead creates a new field called editUserField

I need it to get the values from the input and update the fields in firebase.

like image 671
Gurmukh Singh Avatar asked Dec 21 '25 03:12

Gurmukh Singh


1 Answers

If I understand your intentions correctly, you want the field that is updated to be the value of editUserField.

As an example, if editUserField is "favorite-food" and newUserValue is "pizza", you want { favorite-food: pizza } to be added to the user's data.

If that's the case, you were very close, you just need to wrap editUserField in square brackets to use it's value:

database.update({
  [editUserField]: newUserValue
})

Note: Don't forget to sanitise editUserField! You wouldn't want them setting { isAdmin: true }.

like image 191
samthecodingman Avatar answered Dec 23 '25 17:12

samthecodingman