简体   繁体   中英

Update Firebase with dynamic state properties

I have a Firebase database structure like this:

-KrVtLbX7w8LKHC888cx
   siteInfo
      description: "Udemy is an online learning and teaching market..."
      siteName: "Udemy"
      title: "Udemy Online Courses - Learn Anything, On Your ..."
      type: "video_lecture"
      url: "https://www.udemy.com/"

Each of these siteInfo nodes could potentially contain different keys (ie. one might not have a type and another could have an img ). This makes the data keys relatively dynamic so I can't explicitly set them in firebase.update .

On the frontend, I have a form for the user to edit the site information. The form displays the data in individual input fields for the user to edit depending on which site the user has selected and this is working great.

My problem is submitting an update to the data node that the user is updated.

Right now I'm setting the state for the inputs that have changes like this:

  handleChange = ({target}) => {
    this.setState({
      [target.name]: target.value
    });
  }

And updating the node like this:

   firebase.database().ref().child(`paths/${this.props.uid}/${key}`);
   let siteInfo = this.state;
   firebaseRef.update({
     siteInfo
   });

What this is doing is deleting the entire siteInfo node and adding only those fields that the user has edited. So instead of getting this where only the description has been updated:

-KrVtLbX7w8LKHC888cx
   siteInfo
      description: "The updated description!"
      siteName: "Udemy"
      title: "Udemy Online Courses - Learn Anything, On Your ..."
      type: "video_lecture"
      url: "https://www.udemy.com/"

I'm getting this where it's updating the edits made by the user but everything else is deleted:

-KrVtLbX7w8LKHC888cx
   siteInfo
      description: "The updated description!"
      siteName: "The updated site name!"

I want it to only update those keys that have been updated though. This is my understanding of how the .update method for Firebase is supposed to work but for some reason it's just overwriting everything here.

This was actually a pretty silly oversite on my part. State is already submitting the data as an object so instead of doing this (with the extra object wrapper):

   firebaseRef.update({
     siteInfo
   });

I should have just done this:

   firebaseRef.update(siteInfo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM