Firebase Actions

有 N 人看过

Connect to database

const database = firebase.database();

Bind Data

get data and push them to messages array

database.ref('messages').on('child_added', snapshot => {
  this.messages.push(snapshot.val())
})

// Include ID
// value = snapshot.val() | key = snapshot.key
database.ref('messages').on('child_added', snapshot => {
  this.messages.push({...snapshot.val(), id: snapshot.key})
  console.log(this.messages)
})

Firebase Actions

write data into database

database.ref('messages').push({text: this.messageText, nickname: this.nickname})

// data gets created if the path is not existed
// '/' 代表一個節點
database.ref('nodeOne/nodeTwo/nodeThree').set('third')
database.ref('nodeOne').child('nodeTwo').child('nodethree').set('3rd')

// ps: case sensitive
messages
|--    -L8HkVXx_jUWUXDIVDlR
    |--    nickname: Will
    |-- text: HelloWorld

nodeOne
|--    nodeTwo
    |--    nodeThree: third
    |-- nodethree: 3rd

delete data

database.ref('messages').child('ID').remove()

// delete message and re-render the DOM
database.ref('messages').on('child_removed', snapshot => {
  const indexOfDeletedMsg = this.messages.findIndex( message => message.id === snapshot.key)
  this.messages.splice(indexOfDeletedMsg, 1)
})

remove from DOM will cause other online users not seeing messages been removed, only if they refresh the page

update

// set text value
// database.ref('messages').child('ID').child('text').set('updated value')

database.ref('messages').child('-MHP86XkIhmaSzN9Fodt').update({text: 'updated message'})

// fetch data form the updated ms
database.ref('messages').on('child_changed', snapshot => {
  const updateMessage = this.messages.find(message => message.id === snapshot.key)
  updateMessage.text = snapshot.val().text
})

update multiple records

messages['-Fei3Eee7a/name'] = 'Will'
messages['-L8kSxxE/name'] = 'Will'
messages['-L8kSxxE/text'] = 'new message'

database.ref().update(messages)

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。