DEV Community

Cover image for Retrieving Data from Firebase Realtime Database
Maasa Kono
Maasa Kono

Posted on

Retrieving Data from Firebase Realtime Database

In my previous post, we were successfully able to submit data from the JavaScript form and save it into the Firebase Realtime Database. This was confirmed by checking the Firebase console and seeing that the inputted data was in there. Here is what the database looks like in the console right now:

Alt Text

Retrieving/Reading Data

For this bug tracking app, we will need to extract the inputted information so that it appears on the DOM as an issue ticket.

To start off, let's first set our reference to the location we are looking for in the Firebase database to a variable issuesRef. We will be passing in the child/path of issues/:

const issuesRef = firebase.database().ref('issues/');
Enter fullscreen mode Exit fullscreen mode

Now we can work off of the reference to read the data by using Firebase's on() method, which accepts the value event type and callback function snapshot to get the "DataSnapshot".

If we look at the current data structure as shown in the image above, we see that under the issues/ path, there are nested ID numbers for each issue with their corresponding properties, so we will be iterating through the DataSnapshot. Then, we will call the val() function on each one, which returns a JavaScript object.

We will be using Bootstrap to create a card for each issue ticket, and to get the properties of each issue, simply use dot notation.

The code will look like this:

function readIssues() {
  issuesRef.on("value", function(snapshot) {
    snapshot.forEach(snap => {
      const issue = snap.val();

      document.getElementById("issuesList").innerHTML += `
        <div class="card mb-3" id="${issue.id}" style="width: 25rem">
          <div class="card-body">
            <h3 class="card-title">${issue.desc}</h3>
            <h6>Issue ID: ${issue.id}</h6>
            <p><span class="label label-info">Status: ${issue.status}</span></p>
            <p><span class="glyphicon glyphicon-time">Priority Level: ${issue.priority}</span></p>
            <p><span class="glyphicon glyphicon-user">Assigned to: ${issue.assignedTo}</span></p>
            <button onclick="setStatusClosed('${issue.id}')" id="closeButton" class="btn btn-warning mx-3">Close</button>
            <button onclick="deleteIssue('${issue.id}')" class="btn btn-danger mx-3">Delete</button>
          </div>
        </div>
      `
    })
  }
)}
Enter fullscreen mode Exit fullscreen mode

So now we have the issue tickets appending on the DOM like this:

Alt Text

I will write about updating and delete data with Firebase Realtime Database in my next post.

^_^

Helpful Links

https://firebase.google.com/docs/reference/js/firebase.database.Reference

https://www.tutorialspoint.com/firebase/firebase_read_data.htm

Top comments (0)