angularfire2: Difference between destructive updates ( set() ) and non destructive updates ( update() )

Viewed 306

Currently studying https://github.com/codediodeio/angular-firestarter this repos authentication.

This snippet writes user name and email to realtime db, in the Authentication service of this repo the author uses this method to update user data each time a user registers and signs in.

  //// Helpers ////

  private updateUserData(): void {
    // Writes user name and email to realtime db
    // useful if your app displays information about users or for admin features

    const path = `users/${this.currentUserId}`; // Endpoint on firebase
    const data = {
      email: this.authState.email,
      name: this.authState.displayName
    }

    this.db.object(path).update(data)
      .catch(error => console.log(error));

  }

In my side project that I am currently working on I used the snippet above to write user details to firebase, user details (not only the email and pass) upon registration only not unlike in the repo he used the snippet also to update the user details on signin and register.

In the line of

this.db.object(path).update(data)

I the docs https://github.com/angular/angularfire2/blob/master/docs/2-retrieving-data-as-objects.md#api-summary there are two methods alike, this .update() and set(), it says in the documentation that .update() is non-destructive update and set() destructive update. I tried this two in action and it works the same as the other,

My question is, as I've explained above that I use the snippet upon registration only, what should I use the set() or update()? and what is destructive and non-destructive update, links explaining what are these big help.

1 Answers

As I noticed all frameworks / tools uses same logic for these two actions. So set() destroys object and assigns new values, while update() only updates defined properties.

So, say you have object in db:

car 
 color:  "red",
 engine: "v6"

When you run something like car.set(color = "blue"), object becomes:

car 
 color:  "blue",
 engine: undefined

And doing update(color = "blue") gives:

car 
 color:  "blue",
 engine: "v6"

And this explains why you can't use update() on primitives - they have only one property, so it would be reseted anyway.

Related