クイックリファレンス

Firebase チートシート(Realtime Database・Web API)

Firebase Realtime Database および Web API のクイックリファレンス。初期化、set/get、onValue リアルタイム監視、push、クエリを整理。

· 公開日

Firebase Realtime Database および Web 向け Authentication API のクイックリファレンスです。

初期化と接続設定(Initialization)

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)

データ操作とリアルタイム購読(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())
  }
})

// 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)
)

関連するチートシート

関連テーマ