owned this note
owned this note
Published
Linked with GitHub
---
tags: mstu5013
---
# firebase - write, read
## Overview
There are two basic ways of writing data to a database, `myRef.set()` and `myRef.push()`
## myRef.set()
All reference objects have a .set() method available to write at the defined reference. The pattern is:
`refObject.set(data);`
Now, let's try to set some data by going to our lab excercise file, and set our message.
`messagesRef.set(msg);`
We can also build additional reference and set data by chaining .set after .child
`messagesRef.child("zz").set(msg);`
It would be nice if somehow we can generate a unique ID each time so that additional data won't get deleted. This is where push() comes in.
## myRef.push()
0. the basic syntax for push is:
`refObj.push(data);`
1. now, let's try replacing the .set() command we typed with the following command:
`messagesRef.push(msg);`
Can you go to your firebase account and observe the change in your database structure?
Yes, in addition to saving our data, firebase object now also generates a unique key for each new data entry.
3. Now, inside your saveMsg() function, add two more additional lines at the begining of this function:
```
var key = messagesRef.push().key;
console.log(key);
```
Observe the console.log message as you save data each time.
4. By using unique keys, we can easily have millions of users in our database without worrying about overwriting our data. Often times we create complex data objects with a variety of properties first. Then .push() for a new unique key reference, then .set() the data at that reference.
Now, inside your `msg` variable, besides message property, add an additional id property and set it to the key generated by the .push method.
```javascript=
var msg = {
id: key,
message: this.refs.msgInput.value
};
```
# firebase - read
## intro
Reading data involves three concepts, event lisenter, event trigger, and callback function.
## 1. event listener
So far, we have dealth with event listeners in pure JAVASCRIPT as well as RIOT context.
###### JAVASCIRIPT
```javascript=
var buttonEl = document.querySelector('button');
buttonEl.on('click', function(event) { // event, e, banana - don't matter
console.log(event); // analogous to snapshot
console.log(event.type); // tells us a bit about the event
console.log(event.target); // provides information about the event element
});
```
###### RIOT
<button type="button" onclick={ setUser }>Set Username/UserID</button>
this.setUser = function(e){
}
## 2. event trigger
We will primarily work with three types of trigger events: value, child_added, child_removed.
###### value event
This event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called.
child_added event
This event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.
child_removed event
This event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:
1. A client explicitly calls remove() on that child
2. One of its ancestors a client calls set(null) on that child or one of its ancestors that child has all of its children removed
For more information on event trigger, refer to official firebase documentation [here](https://firebase.google.com/docs/reference/js/firebase.database.Reference#on).
## 3. Callback
Callback, or callafter is a computer science concept that makes one function call on another function passed into it. Since last semester, we have been using a callback function, setTimeout:
```javascript=
setTimeout(alertFunc, 3000);
}
function alertFunc() {
alert("Hello!");
}
```
The main reason why we use callback function is to make sure that certain events happens before the callback function gets called.
## code
Now, let's add this firebase function to retrieve data from our database.
First, declare a message variable of the riot tag to collect data.
```javascript=
var tag = this;
this.messages = [];
```
Then, add the event listener `on` and the event trigger `value` to subscribe for any real-time change to the database:
```javascript=
messagesRef.on('value', function(snap){
//obtain realtime snapshot of data object from firebase
let rawdata = snap.val();
console.log("snap.val", snap.val);
//set up a temporary array to translate js object into javascript array format
var post = [];
for (key in rawdata){
post.push(rawdata[key]);
}
//update riot tag array with translated array value
that.posts = post;
console.log("that.posts", that.posts);
that.update(); // We need to manually update
});
```
==Note for line 10== As you might remember from previous RIOT lectures, RIOT authomatically calls the update() method anytime a UI event is triggered ***within the scope of a tag***. However, Firebase events (e.g. value) are not UI events. Riot is blind to the Firebase events initiated by ***firebase object*** and will not automatically update, even if our data does. Because of this, without accounting for it our component can get out of sync with the data. Thus, we need to create an explicit connection between the Firebase event handler, and our Riot Tag instance through some manual work.
Within our Firebase listener code, we get the data through the snap, then loop through that raw object data to convert it to an array. The for...in goes through each property of the users data object, and pushes each user into an array structure.
## firebase snapshot
Finally, let's take a look at the console log for snap.val, the data object firebase supplies, against the array format we translated ourselves.
![](https://i.imgur.com/1lt6g6e.png)
![](https://i.imgur.com/kKNTVjX.png)
snap.val is a JSON object, a data format widely used as language independent data transfer format between computer systems. It derives from Javascript object literal syntax, borrowing its simplicity, and therefore its syntax is very close to that of JS object.
### syntax
From last semester, we recall that the declaration of a javascript object as:
```javascript=
var car = {
type:"Fiat",
model:"500",
color:"white"
};
```
As for JSON object, we write
```javascript=
{
"name":"John",
"age":30,
"car":null
}
```
If you create an object using JSON format, javascript engine treats it the same as you would have created the object using the object literal. It's safe to say that JSON data is valid Javascript object. However, JSON format is language independent, so it is not a term only limited to javascript alone.
### recap on JS for loop
last semester, when we first started learning JS for loop, we used this kind of syntax:
```
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
```
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
```javascript=
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
for (i = 0; i < person.length; i++) {
text += person[i];
}
```
Later on, when we started learning riot, we switched to a shorthand of writing JS for loop, the `for/in loop`:
```javascript=
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
```
They are both valid ways of writing javascript loop, but the second one allows us to name our own temporary variable, and is a bit shorter, that's all.
### functions
Please refer to this w3school tutorials below for basic properties and functions of JSON object.
https://www.w3schools.com/js/js_json_objects.asp
In particular, in our firebase example, we used the `for loop ` syntax to access its value and push them into a JS array format:
```javascript=
var datafromfb = snap.val;
console.log("snap.val",snap.val);
```
```
{
"-L_nA0fbNmv4WxIdulUQ":{
"id":"shroom",
"message":"sfwefwe"
}
"-L_nA0fbNmv23423ulUQ":{
"id":"banana",
"message":"yellow"
}
"-L_nA0sdfasfwEF3ulUQ":{
"id":"cabbage",
"message":"white"
}
}
```
```javascript=
for (x in datafromfb) {
// 1. declare an temporary JS array
var tempData = [];
// 2. use array.push function to push JSON data into temporary array
tempData.push(datafromfb[key]);
// 3. save tempData into tag property field
tag.messages = tempData;
//4.update riot dom elements to reflect new property value
tag.update();
}
```
In recent years, [as GPU technology advances rapidly](https://www.youtube.com/watch?v=ayPqjPekn7g), 3D rendering is becoming a popular web format. In addition to storing transaction or social media data, JSON format is also increaslying being used to store 3D model's vertex point information.
For example, [this website](https://clara.io/view/a7a20f89-48bc-4bf0-a883-49836b32b5a4) offers 3D models in both traditional 3TL, OBJ format and JSON format. Using JS framework three.js, you can host the JSON file and make this model interact with your audience in real time through javascript canvas.