Database in ForgeStack
ForgeStack provides built-in support for Firebase Firestore, allowing you to easily perform type-safe database operations like adding, reading, and deleting documents.
Setup
To get started with Firestore in your ForgeStack application, ensure you have set up Firebase Firestore in your Firebase project:
- Go to the Firebase Consoleā.
- Select your project.
- Navigate to the āFirestore Databaseā section and click on āCreate Databaseā.
- Choose a starting mode for your security rules and click āEnableā.
Using the useDatabase.ts
The useDatabase.ts
utility wraps common Firestore operations in simplified, reusable functions that return consistent results with success, data, or error fields.
Example
import { addData, getData, deleteData } from "@/hooks/useDatabase";
interface User {
name: string;
email: string;
}
// Add a user
await addData<User>("users", {
name: "name",
email: "email",
});
// Get a user
const result = await getData<User>("users/user123");
if (result.success && result.data) {
console.log("User email:", result.data.email);
}
//Get All Users (From Firestore)
useEffect(() => {
const fetchData = async () => {
const result = await getCollection<User[]>("users");
if (result.success) {
setList(result.data);
} else {
console.error(result.error);
}
};
fetchData();
}, []);
// Delete a user
await deleteData("users/user123");
Features
- Add or update Firestore documents with addData
- Fetch documents with type safety using getData
- Delete documents with deleteData
- Integrates smoothly with ForgeStack authentication