0

I got the below react js cod running with no errors but not sure why it's not displaying anything from the database in the <li> element.

When I console log it in the ComponentWillMount, it pulls the data correctly.

App.js

    class FirebaseDB extends React.Component {
      constructor(props) {
        super(props);
        this.state = { messages: [] };
      }
      componentWillMount(){
        let messagesRef = firebase.database().ref('messages');
        messagesRef.on('child_added', snapshot => {
          let message = { text: snapshot.val(), id: snapshot.key };
          console.log(message);
        })
      }

      render() {
        return (
          <div>
            <ul>
              { /* Render the list of messages */
                this.state.messages.map( message => <li key={message.id}>{message.text}</li> )
              }
            </ul>
          </div>
        );
      }
    }


class App extends Component {
  render() {
    return (
      <FirebaseDB />
    );
  }
}

2 Answers 2

3

You're never setting the state to contain messages so it would never render. You could try

constructor(props) {
  super(props);
  this.state = { messages: [] };
}

componentWillMount(){
  let messagesRef = firebase.database().ref('messages');
  messagesRef.on('child_added', snapshot => {
    let message = { text: snapshot.val(), id: snapshot.key };
    this.setState({
      messages: [...this.state.messages, message],
    });
  })
}
Sign up to request clarification or add additional context in comments.

Comments

1

In react, if you want something to display on screen you need to put on state. Now you do have a messages array on your state, but the data which you are retrieving from firebase is not getting added to state, and as a result nothing is getting rendered.

I am not familiar with firebase per se, but I imagine the basic idea should be something like this.

componentWillMount(){
        let messagesRef = firebase.database().ref('messages');
        messagesRef.on('child_added', snapshot => {
          let message = { text: snapshot.val(), id: snapshot.key };
          const messages = [...this.state.messages]; // copy state so not to mutate
          messages.push(message);
          this.setState({messages}); // this will tell react to re-render with the newly added data
          console.log(message);
        })
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.