Zhenzhen Qi
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- 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.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully