August 23, 2019
Getting Started with the Firebase Realtime Database on the Web, Part 1 – Firecasts

Getting Started with the Firebase Realtime Database on the Web, Part 1 – Firecasts


[MUSIC PLAYING] DAVID EAST: What’s
up, everybody? David here. And on today’s episode
of “Firecasts,” we’re going to be covering the
real-time database and the web. And just as a
reminder to you, this is one of many episodes
on Firebase and the web. So we have a whole series
using Firebase authentication, Firebase Hosting, the
real-time database– pretty much everything Firebase
offers with the web including JavaScript frameworks like
Angular, Ember, and React. So make sure you
subscribe to the channel so you get notified
when we post those. But today, it’s the
real-time database. And we’re specifically going
to be covering real-time events starting with the value
event, which is great when you’re trying
to synchronize things like objects or primitives. So let’s see how
we work with that. So to the left right here,
I have the Data Viewer and the Firebase console. And to the right, I just
have a little web app. And this is my index.html page. And then I also have
an app.js, where I’ve configured my Firebase project. So in this app, I want to
demonstrate how to synchronize events in real-time. So to demonstrate value events,
I am going to create a pre tag. So I’m going to create a pre
and then give it an ID of object because what I’m going to do is
I’m going to display an object inside of this pre. So I’m going to switch
over to my app.js and I’m going to get this
element from the DOM just using document.getElementById
and just pass through the ID of object. And now that I have
this DOM element, I want to create a
database reference so I can synchronize data
from the real-time database to my web app. And as you can see,
there is no data yet. There is pretty much
just this null object. But we’re going to be
changing that in just a bit. So I’m going to
create this reference. And I’m going to
call it DBRef object. And to get it, I’m going
to write Firebase.databas e.ref.childofobject. And essentially what this does
is this ref function gets you to the root of the database. And then calling .child just
creates a child key of object. And then from here, we can
store whatever value we need. Now I’m going to do the
magical part, which is synchronize data in real-time. And there’s one all-powerful
method that you need to know, and that’s the on method. So I’m going to synchronize
the object changes with calling DBRef.object.on. And you need to take note
that right here, I’m calling on the database reference. And this database
reference points at the location of object. So essentially, right here,
we will have data existing at this object location. And what we want to do is
every time this data changes, you want to know about
it in our web app. The first parameter the on
method takes is the event type. And the event type
is how you control the level of synchronization
from the real-time database. So I’m going to use
the value event. Now, the second parameter
is the callback function. And the event type right here
controls when the callback function is called. In the case of the value
event, the function will be called each
and every time there is a change at this
location in the database. So I’m going to create
a callback function using ES2015 arrow functions. And then I’m going to log
this value to the console. So this snap parameter
is essentially called a data snapshot. And the data snapshot
is not just your data. And that’s why I’m
actually calling .val. The data snapshot also returns
lots of other important things, such as the key name and ways
to iterate children and whatnot. But if you want
to get the value, you have to make
sure to call .val. So I pulled up my web
app in the browser. And as you can
see, this value is null, which makes sense because
this is null right here. So let’s go and change that. So I’m going to add a
key of the name object and then a value of hi. And then boom, it changes. So I want to go and
change it again to hello. And you can see that updates. And let’s go and
actually delete. And now we synchronize
back to the null object. So what you might notice is
that every single time we change anything here, it
just started logging it out to the console. Now, regardless of the
change– whether it was something being added, so
a new value, or something being changed to another
value, or even if we deleted the data– it
all logged out to the console. And that’s what the
value event does. It’s sort of a catch-all. And it works really,
really well when you want to
synchronize an object. So rather than
synchronize just a string, let’s go and
synchronize an object. So here in the Data
Viewer, I’m going to add a key name of object. But I’m going to
add other fields. So I’m going to give it
a name of Ms. Object, say its hobbies are
being an object, and the favorite
number, of course– 42. And now when you
look at the console, it’s just a POJO, a Plain
Old JavaScript Object, and has the same values– fav
number, hobbies, and name, just like what we
put in over here. So let’s go and actually
change some of this. So instead of 42,
let’s change it to 45. What do you think is going
to be logged to the console? Do you think that it’s
going to be a, the number 45, or b, the entire object? Tick, tock– which one? Well, let’s hit
Enter and find out. [FANFARE PLAYING] If you selected b,
you are correct. It synchronizes the
entire object, not just the value that was updated. And why is that? Well, the value event is a
catchall event in the sense that every time you update a
value, you’ll get that change. But you don’t just
get the little delta change of the value updated. You get the entire object back. And this is known as
state synchronization. So now that we know how
the value event works, let’s go and display
it in the pre tag. So rather than logging
to the console, I’m going to grab
the pre tag, tap into the inner text, and then
just JSON.stringify snap.value and give it a spacing of 3. And right here, we see
our little JSON output. So we’ll go and
change some things around– change our
number back to 42– that updates in real-time–
update some hobbies. And all of that synchronizes
to and fro in real time. So that’s how you use
value events, which you saw are great for when
you’re synchronizing objects and primitives. So now I have a
question for you. What kind of objects are you
synchronizing in your app? Are you synchronizing users? Are you synchronizing
profiles, which I guess those are the same things? But what are you
synchronizing in your apps? Just let me know in
the comments below. And that’s all for today. But stay tuned for
next time, where we’re going to be covering
child events, which provide you with a lot more granular control
over the items in your list. So I’m just going to head out. [ELEVATOR DINGING] [MUSIC PLAYING]

100 thoughts on “Getting Started with the Firebase Realtime Database on the Web, Part 1 – Firecasts

  1. What am I syncronising? The status and requested status of a fan. If a user asks for a specific speed via the web app, it will push to the fan controller and change to that speed. Vice versa, a user can see the real-time status of the fan (power, speed and temperature). Firebase has made this super easy to do! Thanks for the tutorials!

  2. I have a question on this video,
    I just try to store an Object like following
    Object = {
    attr1 :"hello world ",
    attr2 :{
    lvl2_attr1:"xxy-xy",
    lvl2_attr2:"zzz-zzz",
    childs:["abc","bcd","cde","def"]
    },
    attr3:[{attr1:"afasf"},{attr2:"dafafdas"}]
    };

    but firebase return an error, something like missing the key for attr3

    what is the best practice for handling these kind of Object in firebase?

  3. Hi David, thx for the tutorial, is fantastic.

    I would like to know of any tutorial to pass or map a relational database to NoSQL

  4. HI David Thank you very much for such a nice tutorial … i am facing on issue with real time data base…im getting below error..
    FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'replace' of undefined
    at nh.h.Mc (https://www.gstatic.com/firebasejs/3.3.2/firebase.js:434:247)
    at ef (https://www.gstatic.com/firebasejs/3.3.2/firebase.js:337:303)
    at Rb.te (https://www.gstatic.com/firebasejs/3.3.2/firebase.js:333:203)
    at https://www.gstatic.com/firebasejs/3.3.2/firebase.js:269:2159
    at Ub (https://www.gstatic.com/firebasejs/3.3.2/firebase.js:284:165)
    at Tb (https://www.gstatic.com/firebasejs/3.3.2/firebase.js:269:2143)
    at https://www.gstatic.com/firebasejs/3.3.2/firebase.js:322:1
    at pRTLPCB (https://s-usc1c-nss-113.firebaseio.com/.lp?start=t&ser=84593417&cb=1&v=5&ns=ehms-a6d34:6:55)
    at https://s-usc1c-nss-113.firebaseio.com/.lp?start=t&ser=84593417&cb=1&v=5&ns=ehms-a6d34:9:1
    firebase.js:434 Uncaught TypeError: Cannot read property 'replace' of undefined

    Can you help me in this!
    Thank you.

  5. The callback function of the on method is not firing, can someone help me with this? What im i doing wrong? CODE BELOW

    <!– FIREBASE –>
    <script src="https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script>
    <script>
    // Initialize Firebase
    CODE TO INITIALIZE FIREBASE GOES HERE

    const dbRefObject = firebase.database().ref().child('object');

    dbRefObject.on('value', function (snap) {
    console.log(snap.val());
    });
    </script>

  6. Does anyone know how to get started with firebase on ionic? I'm curious because I'm creating an app and I need to connect it with firebase!

  7. #AskFirebase hi David, you rock. Let's say I use Phantomjs to inject Firebase 3 into webpages for web scraping. How do I push a json object from there into the realtime database? This one is a bonus : why don't you use Firebase for Youtube comments? Peace!

  8. Loading app.js before the <body> throws error: Cannot set property 'innerText' of null.
    I can't figure out why yet.

  9. I am needing to synchronize user inputted, personal user data which should stay specific to that user and that user only. Just to be sure, I should use database rules to set that up correct?

    Also, Is there a way I can organize and serve that users data to them in different ways? So, for example I'd like to give the user the ability to sort through their data items by name or by common color (common item value? grouping by common value?) Is that something that I can do through Firebase by any chance?

  10. hi, i have this proj where i need a data from my computer to be send to the firebase database automatically, is it possible to create such program using c# or c++ thankss..

  11. I'm making an app that needs to display the same content a.s. the website. Can I use firebase to synchronise the website data with the app in realtime?? I'm hoping that you have a video covering this issue.

  12. Hi. Congratulations ! I'm not sure if I'm doing the right thing, but using the script from the previous video (below)
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Firebase Quick Start</title>

    </head>
    <body>
    <h1 id="bigOne"></h1>

    <script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script>
    <script>
    // Initialize Firebase
    var config = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxx.firebaseio.com",
    storageBucket: "xxxx.appspot.com",
    messagingSenderId: "99999999999"
    };
    firebase.initializeApp(config);

    var bigOne = document.getElementById('bigOne');
    var dbRef = firebase.database().ref().child("object");
    dbRef.on('value', snap => bigOne.innerText = snap.val());
    </script>

    </body>
    </html>

    it's working good.

    But using the current script I have nothing from firebase. may you help me ?

  13. Hi , i am new in firebase , i have red your documents and i am using angularfire

    i have a firebase database and i have three object such as country , city and state now i want filter city depends on country .

    i have factory in angular module and i have function getcitybycountryid and passed country and i have used code like this

    stateobject.on("values",function(res){
    res.val()
    }')

    i got result with object and i don't know how to return result via factory function

    please give me the solution as soon as possible.

    Thanks.

  14. hi, can we access firebase database without any listener, because i building an android app which requires a product database which will not be updated every time, so how can i access that data.

  15. Help please! I have the message Uncaught ReferenceError: firebase is not defined!! I have the same code!

  16. I have an hybrid app that works on iOS and Android, can I make 1 firebase databse common,so I can synchronise between them?

  17. Great Post
    Thanks a lot it helped me a lot
    I am also going to share it to my friends and over my social media.
    Also,
    Hackr.io is a great platform to find and share the best tutorials and they have a specific page for Firebase

    This might be useful to your readers: https://hackr.io/tutorials/learn-firebase

  18. No matter what I do, I cannot view anything in my browser's console and I'm using chrome. It works for text but not for console logs.

  19. How to remove observer in tableview? I mean everytime a cell is deque or move out the view when scroll down, how can i remove the observer, because if i scroll down 3 times everytime i tap "like", button, it get called three times, please help, google search long time, and no results

  20. hi.I just want to make a web app and android app using firebase. what i upload in web app it should shown on android app any can help me how can i do that.

  21. i have a question if anyone can help, am i able to get free Account in firebase and use services or i have to buy it ?

  22. hello I love the ease of firebase functions, but I would like to be able to program anywhere I am and I have not found how to do it. They should have how to do this from an APP, or from the web. thus nothing would program the code, I give it to save and it should be published. Thank you

  23. Its clear that Web hosting is for uploading my app to the cloud. But what I am gonna use this firebase realtime database for in a real world app?

  24. hi David , great video can you help me for how i can take request of android app in api with php and response . with firebase realtime database. there is may be multiple request at a time and send mutiple respose form one . please guide me.

  25. hi can you tell how to send push notification for mobilr apps not through firebase console but from client app….plz reply me

  26. 1) How are you using the "localhost:5000"? Were you using FireBase CLI and the $serve command in cmd, some other Google/FireBase feature, or was it some 3rd party source unlreated to Firebase/Google?
    2) In order to view the changes in the DB in the html, is it necessary to be running on a web server, or do you merely need to open the html in a browser with the Firebase code in a <script> tag (i.e. "var config={…}" and the other stuff)?
    3) If I wanted to incorporate FireBase into a WebView Android app, should I use the configuration (and guides) for Android deplayment or for Web?

    I have been trying to work with FireBase for a week, with little to no luck.

  27. how he got localhost :5000 in web browser. HE havent gave any explanation.
    That is where i got struck. please help me

  28. Wait it's not printing anything welp, my code:
    (function() {

    // Initialize Firebase
    var config = {
    This is so that u guys dont steal my app data
    };
    firebase.initializeApp(config);

    // Get elements
    const preObject = document.getElementById("object");

    // Create references
    const dbRefObject = firebase.database().ref().child("object");

    // Sync object changes
    dbRefObject.on("value", snap => console.log(snap.val()));

    }());

  29. I want to do a simple login screen without using authentication? Have my own table of users where where the login is simple their name and postcode

  30. if you use const dbRefObject = firebase.database().ref("object/favNumber"); will you get the reference only to the favNumber? i want to know if the entire object (object) is returned across the web or just the value of favNumber?

    in my chat app im thinking of using the realtime database to store my user profile information like username and user profile image ect. And then for my chat messages using cloud firestore. im trying to figure out the most cost effective way to load profile images in group chats.

  31. this error keeps occurring and I don't know why: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client I am using express and firebase-admin

  32. I'd like to see a SIMPLE (till now I only sow complicated, awkward!) way to do it the other way around: updating a site variable to be persisted in firebase

  33. Watching in 2019. Doesn't work. Nor do the other web examples. Using the CDN to reference the firebase libraries, libraries load just fine however providing config data (which I'm 100% certain is valid config data because it was generated in Firebase console), white listed domains but still get "Uncaught ReferenceError: firebase is not defined" JavaScript error when trying to get the database reference. From searching looks like I'm not the only one… Amazing how a great product can turn to absolutely useless garbage with a problem like this. At this point have lost so much time trying various solutions (changing to previous versions of library, stripping things down to a verbatim copy of what the examples provide… STILL DOES NOT WORK. I see this as a failure on the part of the entire team. Time to move on to another option.

Leave a Reply

Your email address will not be published. Required fields are marked *