David Weiss David Weiss - 2 months ago 35
React JSX Question

Reading data from Firebase 3 into a React component with ES6 syntax

I've been struggling with a simple use case: read a number, ie signed-up user counts, on my React web app from Firebase Database and display it when the page is loaded.

There is documentation for older versions of React and Firebase, but it would seem that this use case should be doable the new way.

Screenshot of my Firebase Database.

import React from 'react'
import {Badge} from 'react-bootstrap'
var firebase = require('firebase')
var config = {
apiKey: "MyKey", // redacted key
authDomain: "dnavid-c48b6.firebaseapp.com",
databaseURL: "https://dnavid-c48b6.firebaseio.com",
storageBucket: "dnavid-c48b6.appspot.com",
var firebaseApp = firebase.initializeApp(config);
var UCRef = firebaseApp.database().ref("numberofusers")
class UserCount extends React.Component{
this.state = {usercount: '3'}
componentDidMount() {
// this.setState({usercount:4}) // This actually works and displays "4"
var uc = UCRef.on('value',function(snapshot){return(snapshot.val())})
this.setState({usercount:uc}) // This does not work
return (
export default UserCount;

In the Chrome debugger (note "debugger" command) I get in the console:

> uc
<. function(snapshot) {
return snapshot.val();


> uc()
Uncaught TypeError: Cannot read property 'val' of undefined(…)

From which I would deduce that since the snapshot is undefined, the event has not been triggered. But this doesn't sound logical as:

  1. componentDidMount has been evaluated (because the component has rendered and the execution reaches it when the debugger stops for inspection)

  2. Firebase documentation claims that the event is triggered, see below "This method is triggered once when the listener is attached".

Value events
You can use the value event to read a static snapshot of the contents
at a given path, as they existed at the time of the event. This method
is triggered once when the listener is attached and again every time
the data, including children, changes. The event callback is passed a
snapshot containing all data at that location, including child data.
If there is no data, the snapshot returned is null.

So, is the listener not being attached? What's going on?


You need to do it like this:

componentDidMount() {
    UCRef.on('value', snapshot => {
      this.setState({usercount: snapshot.val()});

UCRef.on('value', func) would not return you a value. You can get it inside a callback