Gurmukh Singh
Gurmukh Singh

Reputation: 2017

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.

Upvotes: 3

Views: 1318

Answers (1)

samthecodingman
samthecodingman

Reputation: 26296

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

Upvotes: 4

Related Questions