Firebase CRUD Web App with Javascript 🔥 – Part 1 Get/Read Data

   Raja Tamil • Dec 18 • • 3 comments

In this Firebase JavaScript tutorial, I will be guiding you on how to Read/Retrieve Data from Firebase Real-Time Database to your Web App.

This is the first part of the Firebase CRUD Web App with Javascript using Real-Time Database.

🔥 Part #1: Firebase CRUD  JavaScript Tutorial → Setup And Read Data (You Are Here)

🔥 Part #2: Firebase CRUD  JavaScript Tutorial → Insert/Update/Delete Data 

If you’re already familiar with Firebase and JavaScript, then you may want to go to the next section What Are We Building In This Tutorial With Firebase?

What you need to know before reading further:

  1. JSON: You should be familiar with JSON because Firebase uses NoSQL database which means all the data is stored in the JSON tree structure as key-value pairs.
  2. JavaScript: You should be familiar with basics of JavaScript.

Why Firebase?

Have you ever spent most of your time building back-end architecture such as structuring database schema upfront, scalability, and/or user authentication rather than spending time on building your app unique and awesome?

If yes,

Then, you should try Firebase. 🙂

Firebase is a back-end service that your app can interact with. It has a lot of features such as Cloud Firestore, Real-Time Database, User Authentication, File Storage and much more.

With Firebase, we do not have to create database schema upfront because Firebase is very flexible and allows changes to the schema as we progress with our application.

As our application evolves over time,  it’s recommended to build an app with Firebase and change the schema simultaneously based on the requirements.

Firebase lets you query data from the real-time database which is completely different than traditional SQL queries.

I find it’s pretty cool! 😎

What Are We Building?

firebase tutorial read data from readl time database

  1. Get Users List: This simple Javascript app fetches users data from Firebase Real-Time Database using Firebase SDK and populates data on the browser.
  2. Get Selected User: When selecting a user on the left, more information about the user appears on the right.

Pretty simple and straightforward.

Now, we know what we are going to accomplish by the end of this Firebase Javascript Tutorial.

We just need these 6 steps below in order to achieve the final outcome:

STEP #1: Setting Up A Firebase App On The Firebase Console

STEP #2: Setting Up Our Simple User List JavaScript Project

STEP #3: Initialize Firebase Into The App By Adding The Code Snippet

STEP #4: Enable Read And Write Permission To The Firebase Database

STEP #5: Import Users Schema JSON File Into The Database

STEP #6: Read Users Data From The Firebase Using Child_Added() Method

Let’s get started…

Step #1: Setting Up A Firebase App On The Firebase Console

If you already have a Gmail account, go to Firebase Console and log in. The reason you use Gmail is because Firebase has been acquired by Google and has become a part of it.

firebase-project-explorerfirebase-project-explorer

Once you have logged in, you will see the project explorer window like the image above. It may look a bit different depending on when you read this article.

Go ahead and click “Add Project” that will create a modal window in which you can put your project name and select your country. Then click Create Project.

At this point, you have successfully created a Firebase Project. Go ahead and click the project to get into the firebase console.

Step #2: Setting Up Our Simple User List JavaScript Project

The file structure for our simple application is pretty straightforward.

users-app
| - index.html
| - app.js
| - style.css

HTML

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Sample CRUD Firebase Javascript - 01 Read Data</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <h1>
            Firebase CRUD with Vanilla Javascript
            <br />
            <small>
                <em>01 Read Data</em>
            </small>
        </h1>
        <ul id="userList"></ul>
        <div id="userDetail">
            <p>
                Name :
                <strong class="detailName"></strong>
            </p>
            <p>
                Age:
                <strong class="detailAge"></strong>
            </p>
            <p>
                Email:
                <strong class="detailEmail"></strong>
            </p>
        </div>
        <!-- firebase sdk link goes here -->
        <script type="text/javascript" src="app.js"></script>
    </body>
</html>

CSS 

body,
h1,
h2 {
    margin: 0;
    padding: 0;
}
body {
    background: #039be5;
    font-family: Arial, sans-serif;
}
h1 {
    padding: 10px;
    background: #ffcc00;
}
/*---------------------------*/ /* Read Users */ /*---------------------------*/
#userList {
    margin: 0;
    padding: 0;
    width: 200px;
    float: left;
    margin: 10px;
    border: 1px solid #4fc3fc;
}
#userList h2 {
    padding: 10px;
    margin: 0;
    color: white;
}
#userList li {
    padding: 5px 10px;
    border-top: 1px solid #4fc3fc;
    cursor: pointer;
    color: white;
    font-style: italic;
}
#userList li:hover {
    background: #4fc3fc;
}
#userDetail {
    float: left;
    width: 200px;
    margin: 10px;
    margin-left: 0;
    padding: 10px;
    border: 1px solid #4fc3fc;
    color: white;
}

Step #3: Initialize Firebase SDK Into The App By Adding The Code Snippet Via Firebase CDN

Go to Firebase Console.

Click on the Project that you created earlier.

Then, click the Add Firebase to your Web App icon as shown in the image below.

firebase-console

It will open the modal window with code like in the image below.
Firebase JavaScript SDK and Code snippet for initializing firebase

Firebase JavaScript SDK via CDN: Add the script inside the index.html file before app.js script link at the bottom.
Note: If you add the SDK script link after app.js, the app WON’T work.

Firebase Initialize Code Snippet: This code will go to app.js at the top and the starting and ending <script> need to be removed as we are adding the code snippet inside a javascript file.

STEP #4: Enable Read And Write Permission To The Firebase Database

  • Go to Firebase Console.
  • Go to DEVELOPDatabase → Get StartedRULES Tab.
  • Change read and write properties to true.
  • Hit PUBLISH.

That’s it.

Note: As you know, we are NOT using Firebase Authentication in this article. If you want to get started, you can check it out here.

firebase-database-rules-read-write-true

STEP #5: Create And Import JSON Schema Into Firebase Database

  • As Firebase uses the JSON tree structure to store data, you can create a JSON file and structure your data.
  • JSON structure has to be FLAT which means you should try to avoid nesting more than two levels deep.

A sample user JSON file is below.

{
  "users": [{
    "name": "Alex Meraz",
    "age": 24,
    "email": "ameraz@email.com"
  }, {
    "name": "Mohammed Rafi",
    "age": 21,
    "email": "mrafi@email.com"
  }, {
    "name": "Raja Tamil",
    "age": 31,
    "email": "rtamil@email.com"
  }, {
    "name": "Sundar Pichai",
    "age": 21,
    "email": "spichai@email.com"
  }]
}

As you can see in the above JSON code, there is a Users key and it has a few key-value pairs. Pretty straightforward.

Once you save this code as a JSON file, you can import it into the Firebase Database.

  • Go to Firebase Console.
  • Go to DEVELOPDatabase → Get StartedDATA Tab.
  • Click the  ⋮  vertical ellipsis icon at the right, then choose import JSON option from the drop-down.
  • Go ahead and choose the SAVED user JSON file from your computer.
  • Finally, click Import from the modal dialog.

firebase database json data structure

STEP #6: Read Data From Firebase Database

The app.js file will look like this so far.

// Initialize Firebase 
var config = {
  apiKey: "cAIzaSyBnSrCl0UvzIq1yrDMJ3zsdummy",
  authDomain: "asdfadsf-a56e7.firebaseapp.com",
  databaseURL: "httpss://asdfadsf-a56e7.firebaseio.com",
  projectId: "asdfadsf-a56e7",
  storageBucket: "asdfadsf-a56e7.appspot.com",
  messagingSenderId: "104313484945"
};
firebase.initializeApp(config);

Note: You will need to use your version of the code snippet. DO NOT use the code above because it’s a dummy one and will not work.

Database Reference: The first line of the code below has a reference to the main root of the Firebase Database. The second line has a reference to the users key root of the database. If we want to get all the values of the users, we simply use users root.

const dbRef = firebase.database().ref();
const usersRef = dbRef.child('users');

Get User List using Child_Added() method:

const userListUI = document.getElementById("userList");
usersRef.on("child_added", snap => {
    let user = snap.val();
    let $li = document.createElement("li");
    $li.innerHTML = user.name;
    $li.setAttribute("child-key", snap.key);
    $li.addEventListener("click", userClicked) userListUI.append($li);
});

userListUI: Get a DOM element reference for userList.

child_added: Attach a child_added event to the userRef database reference object. It is a Firebase event similar to click event in JavaScript and it typically retrieves a list of items from the Firebase Database.

callback: This event takes TWO arguments,  a string “child_added” and the callback which will run on each interaction.

snap: In each interaction snap object, which is a parameter of the callback,  will hold information about a single user item that we can have access to.

snap.key: This will hold an index number of each user-item as we store them in an array in our Firebase Database JSON tree structure.

snap.val(): val() function will return user object so that we can access any item in that object using dot notation.

snap: Assign each user object to a variable user, at this point I will just need only one value out of the user object which is .name.

li.innerHTML: Create li element and set the name of the user using user.name value.

child-key: Set an attribute called child-key to li which will have the key of each li.

child-key: Set an attribute called child-key to li which will have the key of each li.

userClicked: Attach click event to the list so that if any user clicks on the left we can show more information on the right.

append: This will add li to ul on every iteration.

Show User Detail on li click:

function userClicked(e) {
    var userID = e.target.getAttribute("child-key");
    const userRef = dbRef.child('users/' + userID);
    const userDetailUI = document.getElementById("userDetail");
    userDetailUI.innerHTML = ""
    userRef.on("child_added", snap => {
        var $p = document.createElement("p");
        $p.innerHTML = snap.key + " - " + snap.val() userDetailUI.append($p);
    });
}

userID: Get the childkey attribute on clicking the username (li).

userRef: This time the root is “users/” +  userID. which will give us a specific user object when we use child_added event.

child_added:  get the snap object on each iteration which will have all the key-value pairs of a user object.

Finally, add each key and value into the p element then append them into userDetailUI DOM element.

At this stage you should have an application that can talk to the Firebase Database and retrieve data to the browser using vanilla JavaScript.

If you ever run into an issue while building this application, feel free to comment below and I will respond as soon as I can.

You can find the full source code on GitHub.

UP NEXT  →   🔥 Part #2: Firebase CRUD  JavaScript Tutorial → Insert/Update/Delete Data 

Sharing is caring!