JavaScript

Firebase tips(Database:javascript 1)

More than 1 year has passed since last update.

Firebase with javascript on Chrome.

1. Connect and push data.

push
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase.js"></script>
<script>
  var config = {
    apiKey: 'XXXXXXXXX',
    authDomain: 'XXXXXXX.firebaseapp.com',
    databaseURL: 'https://XXXXXXXX.firebaseio.com/',
    storageBucket: 'XXXXXX.appspot.com',
    messagingSenderId: 'XXXXXXXX',
  };
  firebase.initializeApp(config);
  var database = firebase.database();

  database.ref('coffeeandcode-japan/').push(
    {
      id: 1,
      name: 'coffee'
    }
  );
</script>

result
dbpush.png

2. Set data.

set
  database.ref('coffeeandcode-japan/'+ 'coffee').set(
    {
      id: 1,
      name: 'coffee'
    }
  );

result
setdata.png

3. Update data.

update
  database.ref('coffeeandcode-japan/'+ 'coffee').update(
    {
      id: 2,
      name: 'latte'
    }
  );

result
update.png

4. Remove data.

remove
  database.ref('coffeeandcode-japan/'+ 'coffee').remove();

5. Retrieve single data once.

retrive.once
  database.ref('/coffeeandcode-japan/coffee').once('value').then(
    (snapshot) => {
      console.log('id:' + snapshot.val().id);
      console.log('name:' + snapshot.val().name);
    }
  );

result
retrive_once.png

6. Retrieve multiple data once.

retrive.multiple.once
  database.ref('/coffeeandcode-japan').once('value').then(
    (snapshot) => {
      snapshot.forEach((data)=> {
        console.log("id: " + data.val().id + " name: " + data.val().name);
      });
    }
  );

result
retrive_multi_once.png

7. Retrieve single data when adding a new record.

new.record
"coffee4" {
  "id": 4,
  "name": "test"
}
on.child_add.event
  database.ref('/coffeeandcode-japan').on('child_added', (snapshot) => {
    console.log('id:' + snapshot.val().id);
    console.log('name:' + snapshot.val().name);
  });

result
add_child.png

8. Retrieve single data when removing a record.

remove coffee4 data.

remove.record
  database.ref('/coffeeandcode-japan').on('child_removed', (snapshot) => {
    console.log('id:' + snapshot.val().id);
    console.log('name:' + snapshot.val().name);
  });

result
remove_child.png

9. Retrieve single data when changing a record.

change coffee1's name.

change.record
  database.ref('/coffeeandcode-japan').on('child_changed', (snapshot) => {
    console.log('id:' + snapshot.val().id);
    console.log('name:' + snapshot.val().name);
  });

result
change_child.png