Quick reference for Firebase Realtime Database and Authentication Web APIs.
Initialization
import { initializeApp } from 'firebase/app'
import { getDatabase, ref, set, get, child, onValue } from 'firebase/database'
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id"
}
const app = initializeApp(firebaseConfig)
const db = getDatabase(app)
Data Manipulation
Writing Data (set)
set(ref(db, 'users/' + userId), {
username: "AlanTuring",
email: "[email protected]"
})
Reading Data Once (get)
const dbRef = ref(db)
get(child(dbRef, `users/${userId}`)).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val())
} else {
console.log("No data available")
}
}).catch((error) => {
console.error(error)
})
Realtime Subscriptions (onValue)
const starCountRef = ref(db, 'posts/' + postId + '/starCount')
onValue(starCountRef, (snapshot) => {
const data = snapshot.val()
console.log('Updated star count:', data)
})
Pushing Lists of Data
import { push } from 'firebase/database'
const postListRef = ref(db, 'posts')
const newPostRef = push(postListRef)
set(newPostRef, {
title: "New Post Title",
author: "grace"
})
Queries and Sorting
import { query, orderByChild, limitToFirst } from 'firebase/database'
const recentPostsQuery = query(
ref(db, 'posts'),
orderByChild('createdAt'),
limitToFirst(20)
)
```\n