iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 26
0
Modern Web

Next.js + 各種套件組合系列 第 26

Next.js & Firebase Database (二)

介紹

上篇介紹結構與基本設定,這次介紹的Read跟Write的部分,一樣使用官方的範例來說明,這邊有一點先說明一下因為Firebase是Real Database所以 他是由Server部分主動推到Client的所以要記得有一個監聽的步驟,跟一般要發Request去要資料有點不太一樣

一開始開發的時候因為資料庫預設值是需要auth登入才能讀取,這個部分一開始在學習的時候可以先拿掉

https://ithelp.ithome.com.tw/upload/images/20171225/20103438NZ7676Gfyd.png

接下來先寫入一筆資料 使用set 這裡的userId是驗證過後拿到的userID, set會包含子節點都被覆蓋

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

一般firebase都會使用ref把節點映射參照一份回來本機,然後如果希望遠端有異動的時候的同步更新就會寫一個on去監聽是否有異動

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
  updateStarCount(postElement, snapshot.val());
});

另外也有一種狀態是不需要監聽的,只需要讀取一次這時候就可以使用once


var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
  var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
  // ...
});

因為使用set會把節點下的資料也覆蓋,如果不要全部覆蓋的話就可以使用update對單一節點去處理

function writeNewPost(uid, username, picture, title, body) {
  // A post entry.
  var postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

  // Write the new post's data simultaneously in the posts list and the user's post list.
  var updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return firebase.database().ref().update(updates);
}

範例中有使用到 push這會讓 firebase 新增一個獨一無二的id 然後這邊有使用 update 去更新,這邊同步了兩件事情所以成功的話會同時,失敗也會同時

關於刪除

一般可以使用remove 節點的方式 ,或是使用set null 或是 update 都可以達到remove的功能

移除監聽
要使用監聽時 會使用 on,相對的則使用off

交易處理的時候 有時候本地的資料比較舊可以先同步後再更新 transaction operation 的method transaction

function toggleStar(postRef, uid) {
  postRef.transaction(function(post) {
    if (post) {
      if (post.stars && post.stars[uid]) {
        post.starCount--;
        post.stars[uid] = null;
      } else {
        post.starCount++;
        if (!post.stars) {
          post.stars = {};
        }
        post.stars[uid] = true;
      }
    }
    return post;
  });
}

離線資料

Firebase 寫入資料時都會先反應在寫入在本機端,這樣使用者用起來UX體驗會提高,然後Firebase在去做遠端應該要做的事情,如果資料在網頁關閉時候還沒有寫入遠端則資料會遺失

總結

Firebase提供了許多方法去維護,使用上也不會太難,要注意的是在元件離開使用的時候要記得加上一個off事件把 firebase connect的方法移除


上一篇
Next.js & Firebase Database (一)
下一篇
Next.js & Electron
系列文
Next.js + 各種套件組合30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言