Create a system admin panel using Firebase #3 : Generate unique ID and Retrieve data

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Generate unique ID
  • Retrieve data from the database

Requirements

  • Basic HTML, CSS, and javascript
  • Use firebase
  • Local server (Xampp, Wampp, or etc)

Resources

Difficulty

Basic

Tutorial Content

This tutorial we will continue the previous tutorial series about admin in firebase. For those of you who are new to firebase. I suggest you follow the previous tutorial so you don't feel confused. In this tutorial, I will learn how to display data in our firebase database and we will see how to make CRUD in a real-time database. let's just start this tutorial.

Unique ID in real-time database

  • Make a unique ID

If you are familiar with the SQL database you will know that each table must have a unique ID. But in the real-time database, we don't have the type and unique ID by default, but firebase will generate a unique ID for each data entered. But the unique id that is generated is a random number consisting of numbers and letters which makes it difficult for us to read the unique ID. Therefore we will learn how to create unique IDs with our own desires. We see in the example image below to see the unique ID that was generated automatically by Firebase:

Screenshot_1.png

then how to create our own ID ?, we can create a unique ID by utilizing date time. the time that applies when we enter the data. We can see how it looks like the code below:

Unique ID based on timestamp

 btnSubmit.addEventListener('click', function(){
     //get timestamp
      var timeId = + new Date();

      database.ref('blogs/' + timeId).set({
      title: title.value,
      desc: desc.value,
      time : timeId
    });
    title.value   = '';
    desc.value    = '';
  });
  • var timeId = + new Date(); Make timestamp in javascript.

  • to access events in the Firebase database we must define it first. In the above code, we define it in the var database = firebase.database();.

  • database.ref('blogs/' + timeId).set( )});: our database reference is 'blogs'. blogs is tables or objects from abstraction tables and to make data on blogs we can use a sign / and then the id or parent of the data. In this tutorial, we will make the id come from the timestamp when we enter data

  • and to enter data in the database we can use the set () method. the data we input must be in the form of Object

{
      title: title.value,
      desc: desc.value,
      time : timeId
}

for more details we can see the results as shown below:

ezgif.com-video-to-gif.gif

We can see in the picture above we managed to generate our own id based on the time stamp when the data was added.

Display real-time database data

In the previous tutorial, we have successfully entered data into the database, now we will learn how to display and manage the data using the CRUD method. The first step we will do is create an element that we will use to hold the data we will display.

  • Create the element for display data

We will create an element to display data in the database. in this tutorial, We will retrieve the data in the database. We can see the data in the firebase console like the following:

Screenshot_3.png

We can see in the picture above we have two data on blogs that we will use. Now we will create an element to display data. The following are the elements that we will use:

<div class="row">
      <div id="content">
      </div>
</div>

We will use CSS from bootstrap and we will display the data in the section <div id="content"> </div>.

  • Create a function to retrieve data

To retrieve data we need initialization from our table reference. We can use the blogsRef variable that we have defined in the previous section.

var database  = firebase.database();
var blogsRef  = database.ref('blogs');

We can use event on() that is in firebase.database. We can use it like the code below:

 //Show the data
  blogsRef.on('value', showData, showResErr);
  • in this event we will use 'value' which is useful for retrieving values in our firebase database.

  • We will pass two parameters. The first parameter showData is a function that we make to manage data that has been successfully retrieved from the database. The second parameter showResErr is an optional function to handle errors.


    function showData()

In this function, we will process the data that we have successfully retrieved from the database.

function showData(items) {
    console.log(items.val())
}

In this function, we will accept the parameters that we automatically receive. in this code, the parameter name we receive is items. We can see the contents of the parameters we receive by doing console.log(items.val()).

ezgif.com-video-to-gif (1).gif

we can see in the picture above we have managed to get the data that is in our firebase. then we will display it in the User interface.

Display data

the following is the code in showData().

function showData(items) {
    var content = document.getElementById('content');
    var data    = '';

    items.forEach(function(item) {
      data += '<div class="col-md-4"> <h2>'+ item.val().title + '</h2> <p>'+ item.val().desc +'</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div>';
    })
    content.innerHTML = data;
  }
  • Define element: We will display the data on our element in the element <div id="content"></div>. Therefore we will define the element to make it easier to use the element var content = document.getElementById('content');.

  • forEach data: Because the data in the database is more than one and in the form of an object. then we need to do a looping on our data. In javascript we can loop with the function forEach(). We loop is an element that will display data. therefore we can insert the HTML element we can save into a variable var data = ' '.

  • forEach element: We can foreach html elements and enter values from data in the database like the following.

 data += '<div class="col-md-4"> <h2>'+ item.val().title + '</h2> <p>'+ item.val().desc +'</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div>';

item.val().title and item.val().desc : title and desc are the key in database.

  • Print html: to display html elements with javascript we can use innerHTML content.innerHTML = data;. but we first define the parent element where we will display the element. the parent elements is the content. If it's finished we can see the results in the image below:

ezgif.com-video-to-gif (2).gif

We can see in the picture above, the data we inserted automatically added to our application, that's because we use the realtime database.

We have successfully generated a unique ID and successfully displayed data from the database. we have learned how to manage data that comes from the firebase database that we make. I hope this tutorial can help you better understand Firebase so you can start a project using Firebase. so much from me, see you in the next tutorial. thank you...

Curriculum

Create a system admin panel using Firebase #1 : initialization, user admin settings, and authentication user admin

Create a system admin panel using Firebase #2 : Create a system admin panel using Firebase #2 : Use database and Add child data

Proof of work done

https://github.com/milleaduski/firebaseAdminPanel

Sort:  

Thank you for your contribution @duski.harahap.

Another good tutorial on your part. Thank you for your work in developing these tutorials.
We are waiting for more tutorials!

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

thank you for the review @portugalcoin :)

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 100 upvotes. Your next target is to reach 200 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

The Meet the Steemians Contest is over - Results are coming soon ...

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.032
BTC 60318.52
ETH 2983.06
USDT 1.00
SBD 3.78