Firebase là gì?
Firebase là một nền tảng Backend-as-a-Service (BaaS) được phát triển ban đầu bởi Firebase Inc., và được Google mua lại vào năm 2014.
Nói một cách đơn giản, Firebase cung cấp hạ tầng phía sau (backend) để bạn không cần phải tự cài đặt server, database, hay hệ thống xác thực. Nó cho phép bạn tập trung vào việc xây dựng frontend (giao diện) như React, Angular, hoặc ứng dụng mobile.
Firebase cung cấp những dịch vụ: Authentication,Realtime Database,Cloud Firestore, Cloud Functions, Firebase Hosting, Cloud Storage,Analytics & Crashlytics
Cách bắt đầu với Firebase
Step 1: Đăng ký tài khoản Google nếu bạn chưa có.
Step 2: Tạo Firebase Project
- Truy cập https://console.firebase.google.com
- Nhấn "Add project"
- Đặt tên project (VD: my-react-app)
- Bật Google Analytics nếu muốn
- Nhấn Create Project
Step 3: Tạo Realtime Database
Trong Firebase Console → Mục bên trái chọn Build → Realtime Database-> “Create Database”
Chọn vị trí (chọn Singapore)
Chọn chế độ bảo mật:
- Start in test mode (cho phép mọi người đọc/ghi) – phù hợp để học/lab
- Sau này bạn có thể cập nhật rule lại để bảo mật
Step 4: Tạo Collection (Node)
Trong Realtime Database, không có khái niệm "collection" như Firestore. Mọi dữ liệu là dạng JSON lồng nhau, tổ chức theo node / key / value
"users": {
"1": "Washington",
"2": "Lincoln",
"3": "Roosevelt"
}
Sau khi có dữ liệu, bạn có thể dùng Firebase SDK để đọc dữ liệu từ React như sau:
Cài thêm SDK cho Realtime Database:
npm install firebase
Tạo file src\fireBaseConfig.tsx;
import { initializeApp } from "firebase/app";
const config = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "https://YOUR_PROJECT.firebaseio.com",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
const fireBaseConfig = initializeApp(config);
export default fireBaseConfig;
Thêm Component User: components\user\User.tsx
import { useEffect, useState } from "react";
import fireBaseConfig from "../../fireBaseConfig";
import { getDatabase, ref, onValue } from 'firebase/database';
const User = () => {
const [users, setUsers] = useState<string[]>([]);
useEffect(() => {
const db = getDatabase(fireBaseConfig);
const usersRef = ref(db, 'users');
const unsubscribe = onValue(usersRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const userList = Object.values(data) as string[];
setUsers(userList);
}
});
return () => unsubscribe(); // cleanup listener
}, []);
return (
<div className="p-4">
<h2 className="text-xl font-bold mb-2">Danh sách người dùng</h2>
<ul className="list-disc list-inside">
{users.map((name, index) => (
<li key={index}>{name}</li>
))}
</ul>
</div>
);
}
Giải thích
export declare function getDatabase(app?: FirebaseApp, url?: string): FirebaseDatabase;
getDatabase(): Lấy đối tượng Firebase Realtime Database từ app đã khởi tạo. Nó kết nối với database của bạn qua cấu hình firebaseConfig.
- app: App Firebase đã được khởi tạo (initializeApp(config))
- url: (tùy chọn) là địa chỉ cụ thể của Realtime Database bạn muốn kết nối tới. Dùng url khi có nhiều instance Realtime DB
export declare function ref(db: FirebaseDatabase, path?: string): Reference;
Ex: ref(db, 'users')
Tạo đường dẫn (reference) đến một vị trí cụ thể trong Firebase Database. Ví dụ: ref(db, 'users') sẽ trỏ đến đường dẫn /users.
export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;
Đây là hàm listener dùng để lắng nghe dữ liệu real-time. Khi có thay đổi tại usersRef, nó sẽ gọi callback mà bạn truyền vào.
const unsubscribe = onValue(usersRef, (snapshot) => {
const data = snapshot.val();
// Xử lý dữ liệu ở đây...
});
unsubscribe: Ngắt kết nối khi component bị hủy

Nhận xét
Đăng nhận xét