Firebase Read operation.
1. Set up firebase project
2. Setting Up Simple User List
users-app
| - index.html
| - app.js
| - style.css
<!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>
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;
}
3. Initialize Firebase SDK Into The App, By Adding The Code Snippet Via Firebase CDN
Go to the Firebase Console.
Click on the Project that you created earlier.
Then, click the Add Firebase to your web app icon.
I onda imas:
Taj SDK link treba da staviš pre (u html), poziva glavnog javascript fajla (app.js).
To ti je ovo (ali ovo je koristeći Firebase JavaScript SDK via CDN [Add the script inside the index.html file before the app.js script link at the bottom.
Note: If you add the SDK script link after app.js, the app WON’T work.] ) :
<!-- znaci, ovo isto ide pre izvrsavanja onih stvari da bi ucitao firebase.. -->
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script type="text/javascript" src="app.js"></script>
A ovo dole ispod toga je Firebase Initialize Code Snippet.
This code will go to the 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.
Izbaci ti šta treba da ubaciš, ali ti mozes to da kopiraš, ali da kada kreiraš, da ideš na ovaj, dio (klikneš settings na to kliknuto app, i ideš na "config")
5. Read Data From Firebase Database
The app.js
file will look like this so far.
// Initialize Firebase
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var config = {
apiKey: "AIzaSyAYnVFJmAx2O1JWdzWYPRcDTn4VDRNuvAw",
authDomain: "paws-69846.firebaseapp.com",
databaseURL: "https://paws-69846-default-rtdb.firebaseio.com",
projectId: "paws-69846",
storageBucket: "paws-69846.appspot.com",
messagingSenderId: "721789489246",
appId: "1:721789489246:web:99851cb41cddd2b6c2e4cf",
measurementId: "G-FJRECVX9J2"
};
// inicijalizuj
firebase.initializeApp(config);
- 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 the 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(): The val() function will return the 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.
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 child–key 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 the child_added event.
child_added: Get the snap object on each iteration which will have all the key-value pairs of a user object.
Top comments (0)