AngularM
AngularM

Reputation: 16618

Firebase - How can I update an object in the Firebase Realtime Database

How to update an existing object.

I'm having trouble updating an objectin the Firebase Realtime Database.

Does anyone know how to do this?

I'm using: Angular and TypeScript.

Here is my current TypeScript code:

updateProfile = (profile): any => {
  return new Promise((resolve, reject) => { 
    var refProfile = new Firebase("https://poolcover.firebaseio.com/profiles");

    refProfile.update(profile, function(error) {
      if (error) {
        console.log('Synchronization failed');
        resolve(false); 
      } else {
        console.log('Synchronization succeeded');
        resolve(true); 
      }
    });
  })  
}

This is the database table and profile I'm looking to update:

enter image description here

Upvotes: 2

Views: 7115

Answers (1)

David East
David East

Reputation: 32604

You need to find the key for the profile. When storing user data, you should key off of the uid not an id with .push().

Also, don't use the completed callback use a listener instead.

A completed callback waits for a server response, where a listener fires off locally first. So a listener callback is faster.

constructor() {
  this.profileRef = new Firebase("<my-firebase-app>/profiles");
  var currentUser = this.profileRef.getAuth(); // if authenticated 
  this.userRef = refProfile.child(currentUser.uid);
  userRef.on('value', (snap) => {
    console.log('Profile updated');
    console.log(snap.val()); // update profile info
  });
}

updateProfile(profile) {
  this.userRef.update(profile);
}

Upvotes: 1

Related Questions