Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

aurel kurtula
aurel kurtula

Posted on • Edited on

     

Introduction to firebase's real-time database

Firebase is a platform that provides us with a number of google cloud services that are exposed through simple SDKs. The main features provided are: database, storage and authentication. In this tutorial I am going to connect to a database and show how we could perform CRUD actions (that is, how we can create, read, modify and delete data).

Let's start by going to firebase consoleconsole.firebase.google.com (clearly you have to be logged to your google account). Then just click on "Add Project" and give your project a name and create the project.

After that you are imediately directed inside your project. As you can see, you can easily link this project to an iOS, Android or a web app. We are going to use firebase with client side JavaScript, hence click on "Add Firebase to your web app"

There you get the information which you'll need to connect to this firebase project.

I covered the important information to mainly highlight that that information is private and the way we're working with this data today is not secure at all, but it's a fantastic way to get our head around how firebase works. In later tutorials we'll cover more secure approaches.

Before we start writing code, let's make sure that we are able to read and write to the database without needing an authentication.Clearly this is bad practice and should not be done in production mode but we are experimenting. Authentication will be covered at a later date

Close the above window and navigate to Database (located on the left) select "Realtime Database" then click on "rules", then just change"auth != null" totrue for both read and write and select publish. The warning is logical but that's ok.

Start the project

We'll be working with client side JavaScript. If you want to follow along all you'll need is anindex.html and ascript.js file. Link thescript.js file and thefirebase.js file (which firebase itself instructed that we do) to the html file, something like so:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Playing with Firebase</title>  <script type="text/javascript" src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script></head><body>  <script type="text/javascript" src="script.js"></script></body></html>
Enter fullscreen modeExit fullscreen mode

In reality you might have more html, but that's just to illustrate how to setup firebase. In this tutorial I'll illustrate how data can be managed in firebase, where you place the results is up to you.

Insidescript.js we'll start by pasting the initial code that firebase gave us above.

var config = {  apiKey: "*******************",  authDomain: "******.firebaseapp.com",  databaseURL: "https://******.firebaseio.com",  projectId: "******",  storageBucket: "******.appspot.com",  messagingSenderId: "***************"};firebase.initializeApp(config);
Enter fullscreen modeExit fullscreen mode

Firebase gives us a bunch of methods. Notably,auth(),database() andstorage(). All of which respond to the services Firebase provides. In this tutorial we are working only with the database so let's add that to our code

const database = firebase.database()
Enter fullscreen modeExit fullscreen mode

Writing to the database

We are dealing with a non-sql database. The data is stored and organised as JSON or as a javaScript object. Consider the following as the kind of data we want to store in the database

{  "items" : {    "-L-stEfbU_e13v8dVUwe" : {      "archived" : false,      "completed" : false,      "item" : "Get milk"    }  }}
Enter fullscreen modeExit fullscreen mode

So, we want to push items into an items object. If you come from an SQL background, think of it as; we want to push data to an items table.

We therefore need to specify the name of the parent property which would then hold our data. We do that like so

const ref = database.ref('items');
Enter fullscreen modeExit fullscreen mode

All we need to do now is treatref as a container where we add or read it's content and the changes would be reflected into the database.

database.ref('items') returns a bunch of methods, one of which ispush, lets use it:

ref.push({  item: "Get Milk",  completed: false,  archived: false})
Enter fullscreen modeExit fullscreen mode

Immediately, our new object is added to theitems object in the database. Firebase automatically creates a unique identifier for this new object.

Thepush() method returns an object also, we can access that, as we would normally do, by attaching the above into a variable

const result = ref.push({...})
Enter fullscreen modeExit fullscreen mode

If you consoleresult, you'll see that we're able to use methods such ascatch to catch any error that might have occurred whilst pushing the new object to the database, or athen method to give us the opportunity to do something when operation is complete. But also we're able to access the unique identifier that firebase auto-generated by runningresult.key

Reading data

There are two ways to read from the database. There's usingonce() oron(). As their names suggest,once() reads the data one time but doesn't listen for the changes, where ason() fetches the data every time it changes.

ref.on('value',callback(data))
Enter fullscreen modeExit fullscreen mode

once() is writen in the exact same way

ref.once('value',callback(data))
Enter fullscreen modeExit fullscreen mode

Bothonce() andon() observe events.value is an event that "[reads] and [listens] for changes to the entire contents of a path" -docs. (And the content path is what we specified indatabase.ref('items'),items being the content path)

One of many ways you might want to work with the resulting data is to loop through the object and inject it into your DOM.

let li = document.getElementById('items')ref.on('value', function(data){  let objKey = Object.keys(data.val());  for(obj in objKey){    let key = objKey[obj];    li.innerHTML +=`      <li>${data.val()[key].item}</li>    `  }})
Enter fullscreen modeExit fullscreen mode

Updating data

As mentioned above, each object we add to the database gets a newly generated identifier. To update one of these objecs, we need to reach to that object by using it's identifier, then calling anupdate() method on it.

ref.update({  "-L-t-BeCnrFAfcrYLMjE" : {    "archived" : false,    "completed" : true,    "item" : "Get milk"  }})
Enter fullscreen modeExit fullscreen mode

Clearly we would not need to hardcode the unique identifier like that, but that's how the object is updated.

Deleting objects

Removing objects is very easy. There are multiple ways of doing it. We can just callremove() as we reference the object we want to delete:

database.ref('items/-L-t-BeCnrFAfcrYLMjE').remove();
Enter fullscreen modeExit fullscreen mode

Or we could use the update method and "update" the object tonull, causing it to be removed

ref.update({ "-L-t-BeCnrFAfcrYLMjE" : null })
Enter fullscreen modeExit fullscreen mode




Conclusion

That's it for the basics of interacting with Firebase real-time database. If you open the same application in two separate browsers, simulating different clients, all database changes would be reflected to all the clients, hence real-time.

Next,read the tutorial to learn how to manage your asset files with firebase's storage service

Top comments(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
olivermensahdev profile image
Oliver Mensah
Into Software Engineering(SWE) 💻 & Developer Relations(DevRel) 🥑
  • Email
  • Location
    Sefwi Bekwai, Western North, Ghana
  • Education
    Ashesi University, Ghana
  • Work
    Software Engineer
  • Joined

Great piece but I think we have other great features of Firebase aside what you mentioned. Like the cloud functions comes in handy when you want to write server side code that operates based on certain events. One other feature I also like is the hosting services that allows you to host you app both static and dynamic.

CollapseExpand
 
aurelkurtula profile image
aurel kurtula
I love JavaScript, reading books, drinking coffee and taking notes.
  • Joined

Thank you

Of course I plan to cover almost all the features.

This tutorial was to cover the database. The nexttutorial was storage, the upcoming will cover authentication. Then I'll cover hosting. I didn't want to cover the cloud functions but I might.

One by one. I wanted to explore each feature separately so that I can go in detail.

CollapseExpand
 
olivermensahdev profile image
Oliver Mensah
Into Software Engineering(SWE) 💻 & Developer Relations(DevRel) 🥑
  • Email
  • Location
    Sefwi Bekwai, Western North, Ghana
  • Education
    Ashesi University, Ghana
  • Work
    Software Engineer
  • Joined

Okay. That is cool. I will learn a lot.

CollapseExpand
 
troyb408 profile image
Troy Bryant
  • Joined

Great article. Are you doing one on authentication with facebook?

CollapseExpand
 
aurelkurtula profile image
aurel kurtula
I love JavaScript, reading books, drinking coffee and taking notes.
  • Joined

Thanks.

I coveredstorage the other day, the next tutorial is going to be all about authentication. I want to just cover github authentication but yes I'll do facebook as well.

CollapseExpand
 
jorotenev profile image
Georgi Tenev
  • Joined

Thanks a lot for the article!! Looking forward to an article about the production mode security practices :)

CollapseExpand
 
aurelkurtula profile image
aurel kurtula
I love JavaScript, reading books, drinking coffee and taking notes.
  • Joined
• Edited on• Edited

Thanks,

Security in production mode is going to be the fourth article in this mini series.

The second article is going to explore storage

CollapseExpand
 
curiosityspeak profile image
Curiosity's Peak
  • Joined

I can't understand how to order data, make things like pagination etc. where can I find resources?

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I love JavaScript, reading books, drinking coffee and taking notes.
  • Joined

More fromaurel kurtula

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp