简体   繁体   中英

How to use child_added correctly in react/firebase

I'm not entirely sure this is the right way to go about it but I am trying to append to my firebase database different messages that a user might receive.

I have this function that is called when I click a button:

sendMessageButtonClicked: function(){
      var loggedInUser = this.state.loggedInUserObject;
      var databaseRef = firebase.database().ref().child('users/' + loggedInUser.useruid + '/messages/');
      databaseRef.on('child_added', function(snapshot){
        var messageBodyValue = document.getElementById('message').value;
        var chat = snapshot.val();
        var msg = document.getElementById('msgs');
        msg.appendChild(messageBodyValue);
      })
    },

But I am getting the error:

failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

I can confirm messageBodyValue is what ever i type in eg 'hello' chat is an object with 3 properties msg is an id.

so i am trying to append a child to this html element every time I send it.

I want my firebase JSON to go from:

 "messages" : {
        "PHS2DwlCZ0RJaylhJ0FNgEiNLug2" : {
          "messageBody" : "Hello, how are you?",
          "receiverName" : "Lucy",
          "receiverUseruid" : "PHS2DwlCZ0RJaylhJ0FNgEiNLug2"
        }

to:

  "messages" : {
        "PHS2DwlCZ0RJaylhJ0FNgEiNLug2" : {
          "messageBody" : "Hello, how are you?",
          "messageBody" : "another msg",
          "messageBody" : "another child message",
          "receiverName" : "Lucy",
          "receiverUseruid" : "PHS2DwlCZ0RJaylhJ0FNgEiNLug2"
        }

You need to wrap messageBodyValue inside a DOM node before passing it into appendChild .

var messageBodyValue = document.getElementById('message').value;
var messageElement = document.createTextNode(messageBodyValue);
var msg = document.getElementById('msgs');
msg.appendChild(messageElement);

This shouldn't be affecting the structure of the data in your Firebase instance, but it looks like there might be a problem with the way you're trying to store the data.

"PHS2DwlCZ0RJaylhJ0FNgEiNLug2" : {
  "messageBody" : "Hello, how are you?",
  "messageBody" : "another msg",
  "messageBody" : "another child message",
  "receiverName" : "Lucy",
  "receiverUseruid" : "PHS2DwlCZ0RJaylhJ0FNgEiNLug2"
}

An object can't have multiple messageBody properties.

Instead, you'd have to get hold of the messageBody ref, then push further values onto it.

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