Συνοπτικός οδηγός για το Firebase Realtime Database και τα Web APIs ελέγχου ταυτότητας.
Αρχικοποίηση και Σύνδεση
import { initializeApp } from 'firebase/app'
import { getDatabase, ref, set, get, child, onValue, push, query, orderByChild, limitToFirst } 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)
Χειρισμός Δεδομένων και Συνδρομές
// 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())
}
})
// Realtime Subscriptions (onValue)
const starCountRef = ref(db, 'posts/' + postId + '/starCount')
onValue(starCountRef, (snapshot) => {
console.log('Updated star count:', snapshot.val())
})
// Pushing Lists of Data
const postListRef = ref(db, 'posts')
const newPostRef = push(postListRef)
set(newPostRef, {
title: "New Post Title",
author: "grace"
})
// Queries and Sorting
const recentPostsQuery = query(
ref(db, 'posts'),
orderByChild('createdAt'),
limitToFirst(20)
)