Firebase Flashcards
What is firebase?
Backend as a service
how to establish a connection to firebase database
import * as firebase from ‘firebase’;
const firebaseConfig = {
apiKey: “AIzaSyAdcTBkULme5gAMwksm7n4aSm9uRVXVkTQ”,
authDomain: “expensify-3a1e5.firebaseapp.com”,
databaseURL: “https://expensify-3a1e5.firebaseio.com”,
projectId: “expensify-3a1e5”,
storageBucket: “expensify-3a1e5.appspot.com”,
messagingSenderId: “932279113711”,
appId: “1:932279113711:web:d77772e36517d5065b881a”
};
firebase.initializeApp(firebaseConfig);
How to write to the database?
firebase.database().ref().set({name:’Chris’});
How to update a value in the database?
firebase.database(‘user’).ref(‘name’).set({name:’Chris’});
How to remove data values from database?
firebase.database(‘user’).ref(‘name’).remove();
How to update values in the database?
firebase.database(‘user’).ref().update({key:value});
when updating children of a property, need to use {key/child:’value’}
How to read from the databse?
database.ref('propertyToAccess').once('value').then((snapshot)=>{ const val = snapshot.val() console.log(val) }).catch((error)=>{ console.log(error) })
How to subsribe to a database so that it notifies you each time a change occurs
database.ref().on(‘value’,(snapshot)=>{
console.log(snapshot.val())
})
How to remove a subscription to database?
database.ref().off((snapshot)=>{
console.log(snapshot.val())
})
What datatype does firebase database not support?
Arrays
What happens when you try and save an array in firebase database?
firebase turns the array into an object with array indices as keys
what does database.ref().push() do?
it creates a unique id for the element and saves the element as a child of the unique id
When saving and retrieving arrays from firebase database, which methods should be used
Storing and array
expenses.forEach((expense)=>{
database.ref(expenses).push(expense)
})
when retreiving, call forEach on snapshot
database.ref().once('value').then((snapshot)=>{ const expenses = [] snapshot.forEach((childSnapshot)=>{ expenses.push({ id:childSnapshot.key, ...childSnapshot.val() }) })
}).catch((error)=>{
console.log(error)
})
name the different subcription methods
val()
child_removed()
child_changed()
child_added()