DEV Community

Cover image for Creating a Database - Part 2 - Firebase Basics Series
Areeb ur Rub
Areeb ur Rub

Posted on • Updated on

Creating a Database - Part 2 - Firebase Basics Series

So in the previous part of this series we are done creating a project and a app in firebase console now in this part we will see how to connect your app to firebase and will be creating a database.
firebase-database
So we will be working inside the build section of firebase console to first build our Web App and we can see there are two types of database in firebase the Firestore and Realtime Database.

Both Firestore and Realtime Db are almost same there are only some difference that are,

  • Firestore keeps data in a more structured way in form of Documents and Collections where as Realtime Db keep like in JSON format.
  • There are more complex way to query Firestore Db than Realtime Db

We will be using Realtime database for now but will come to Firestore also in some next part.

Let's build a Todo list

Now, we will build a todo app first to store our tasks in database and see how we can update and delete it using firebase Realtime database.

create folder todo So first create a folder and open it in an code editor (I am using VS Code), then create some files as index.html, style.css and app.js open the index.html and add some basic basic HTML code.
adding scripts Add the Firebase SDK Script (which we got while creating our web app) at the bottom of body tag and then we will be ready to use firebase in our Web-App

if you don't have it go to project settings in firebase console and scroll to the bottom you will find the script there.

Do you need to protect the SDK Script,

You might think that why to paste the whole API keys in a public file, because in firebase we can write rules means the API can be used to retrieve only those which are set to public aur which one is allowed to view not anyone can have anyone's data we as developers can set what data to be shared by setting up rules in firebase console.

Yeah, it's safe to keep the scripts in public but only when you have setup your rules properly.

Creating a basic layout

So before creating a database we will make a simple layout for our todo list, we will have a Text field with add button , a list of tasks, a delete and update button.

Here's one layout I created now we will add functionality to it.

Adding Realtime database SDK script

to use Realtime data base we have to add it's script to our code and we can get it from the firebase documentation firebase.google.com/docs/web/setup.

<script src="https://www.gstatic.com/firebasejs/8.6.7/firebase-database.js"></script>
Enter fullscreen mode Exit fullscreen mode

Before we start adding data to our database we have to enable it first RT Db enable
for now we will be keeping it on test mode, means we are not setting up rules and anyone can use it, but we will change the rules afterwards.

How to Use?

in app.js file first we will call the firebase.database() instance and save it as database

const database = firebase.database();
Enter fullscreen mode Exit fullscreen mode

and now we will can use database.ref('task') to refer the task reference in our database.

reference is the location for objects in database which are structured in a json format like:

task{
    task1:{
        task:'this is your task',
        createdBy: 'Areeb ur Rub'

    }
    task2:{
        task:'this is your task two',
        createdBy: 'Areeb ur Rub'

    }
}
Enter fullscreen mode Exit fullscreen mode

Adding data

To add a data we specify reference and then we can add a object to that reference and set the value of object using .set() to enter data.

so this is the code which will take task on submit and add it to our database.

const form = document.getElementById('task-form');
const taskInput = document.getElementById('task-input');

const database = firebase.database();
const tasks = database.ref('tasks');
console.log('ok')

form.onsubmit = (e) => {
    e.preventDefault();
    tasks.push().set({
        'task' : taskInput.value
    })
    taskInput.value = ''
}

Enter fullscreen mode Exit fullscreen mode

Read the data from database

There are two method to read data from Realtime database .on() and .once() , the only difference between both is that .once only read data on load of document where as .on read the data when ever the data is changed.

we will use .on as we want to change the Tasklist as a new task is added

tasks.once('value',(snapshot) => {
    data = snapshot.val()
    for(var taskID in data){
        console.log('task is '+ data[taskID].task)
    }
})
Enter fullscreen mode Exit fullscreen mode

using the above script we will read the tasks from the database and console log it. (Press CTRL+SHIFT+J to open console)

Now to display the added task we will replace the console log with the list item tag which I have created earlier.

I will add each task in the taskList using += and then use back ticks ( )to add multiline string and replace the task text with${data[taskID].task}` and now all our tasks are being displayed.

on every change in document this function will be called with the latest snap shot so I will clear the whole list using taskList.innerHTML = ''; and add all the data.

`
taskList.innerHTML = '';

for(var taskID in data){
    taskList.innerHTML += `
        <li>
            <div class="task-card">
                <button class="update">
                    <span class="fas fa-edit"></span>
                </button>

                <p>${data[taskID].task}</p>

                <button class="delete">
                    <span class="fas fa-trash"></span>
                </button>
            </div>
        </li>
    `
}
Enter fullscreen mode Exit fullscreen mode

`
It is working

Try it yourself,



Till now we have used Realtime Db SDK in our web app and have added our data from web app to the database.

To be continued ....

This is getting too long for this post, so we will take this project to next post.

Follow me for more,


Top comments (0)