How do you perform read and write operations and query data from Firebase Realtime Database, where the traditional syntax in v8 goes like this:
const snapshot = await firebase.database().ref("/path").once("value")
Considering the sample data:
{
"users" : {
"user1" : {
"age" : 34,
"name" : "user1"
},
"user2" : {
"age" : 23,
"name" : "user2"
},
"user345" : {
"age" : 19,
"name" : "user345"
},
"user4" : {
"age" : 15,
"name" : "user4"
},
"user56" : {
"age" : 45,
"name" : "user56"
},
"user9435" : {
"age" : 8,
"name" : "user9435"
}
}
}
Also how would you use the methods equalTo(), orderByChild(), etc
?
How do you perform read and write operations and query data from Firebase Realtime Database, where the traditional syntax in v8 goes like this:
const snapshot = await firebase.database().ref("/path").once("value")
Considering the sample data:
{
"users" : {
"user1" : {
"age" : 34,
"name" : "user1"
},
"user2" : {
"age" : 23,
"name" : "user2"
},
"user345" : {
"age" : 19,
"name" : "user345"
},
"user4" : {
"age" : 15,
"name" : "user4"
},
"user56" : {
"age" : 45,
"name" : "user56"
},
"user9435" : {
"age" : 8,
"name" : "user9435"
}
}
}
Also how would you use the methods equalTo(), orderByChild(), etc
?
1 Answer
Reset to default 21Disclaimer: The v9 modular SDK is a beta release. The syntax may (or may not) change but I'll try to update the answer if any asap. Benefits of this upgrade can be found here.
The modular SDK cannot be used over CDN and you need to use npm or yarn for the time being. I've tested this in a Vue web-app.
1. Initialize the Firebase App:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "<api-key>",
authDomain: "<project-id>.firebaseapp.com",
databaseURL: "https://<project-id>.firebaseio.com",
projectId: "<project-id>",
storageBucket: "<project-id>.appspot.com",
messagingSenderId: "0000000000",
appId: "<app-id>",
}
const app = initializeApp(firebaseConfig)
2. Create a Database Instance and Reference:
import { getDatabase, ref } from "firebase/database"
const db = getDatabase(app) // <-- Pass in the initialized app
//Creating the reference (The path in db you are trying to read/write/update)
const dbRef = ref("/users")
3. Read Operation and Listeners:
You need to use get()
method to retrieve data which accepts a query as parameter. If you are simply reading the data without any sorting or filtering, just pass the reference created above in the query()
. (Note: Passing the reference directly in get() works in this case)
import { get, query, onValue } from "firebase/database"
const usersSnapshot = await get(query(dbRef)) //This should get the whole users node from db.
//To add a listener you can use the onValue() method like,
onValue(query(dbRef), snapshot => {
console.log(snapshot.val())
})
//
In v8, the syntax for events looks like .on("event_name")
. In v9, all events are a method which can be used this way:
import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database"
onChildAdded(query(dbRef), (snapshot) => {
console.log("child added");
console.log(snapshot.val()); // Logs newly added child
});
onChildChanged(query(dbRef), (snapshot) => {
console.log("child changed")
console.log(snapshot.val()); // Logs updated value of changed child
});
onChildRemoved(query(dbRef), (snapshot) => {
console.log("child removed");
console.log(snapshot.val()); // Logs value of removed child
});
4. Writing Data:
// You maybe have figured out the upgrade trend ¯\_(ツ)_/¯
import { set, update } from "firebase/database"
const newUserName = "user1122"
const userRef = ref(`users/${newUserName}`)
await set(userRef, {name: newUserName, age: 11})
await update(userRef, {age: 12})
5. Working with lists:
This is best part and it now kind of feels similar to adding stages in a MongoDB Aggregation.
import { query, orderByChild, orderByValue, orderByKey, limitToLast } from "firebase/database"
//Example: getting 3 youngest users from the db
const usersSnapshot = await get(query(dbRef, ...[orderByChild("age"), limitToFirst(3)]))
The first parameter in the query()
is the Database Reference and all following parameters are QueryConstraints and can be either of these methods: 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';
. You can pass them as individual parameters instead of using spread operator as I've used.
I've found no issues using the modular SDK so far. Just make sure you've imported all things which are needed.
PS: Just in-case if you use Vue, React or any framework with hot-reload when developing, you might encounter the "Firebase App named '[DEFAULT]' already exists (app/duplicate-app)" error. Checking if firebase.apps.length
is 0 helps and that's done this way in modular SDK:
import { getApps, initializeApp } from "firebase/app"
if (!getApps().length) initializeApp(firebaseConfig)