I want to create a new doc in firebase/firestore, in runTransaction function of firebase in react. But I don't know how to create a reference for new doc in react firebase?
import { useEffect, useState } from "react";
import "../../css/centerLoader.css";
import { MainFlexLoader } from "../CenterLoader";
import { auth } from "../../firebase-config";
import { db } from "../../firebase-config";
import { collection, doc, runTransaction } from "firebase/firestore";
export default function Records() {
const [isLoading, setIsLoading] = useState(true);
const [total, setTotal] = useState(0);
const initailizeData = async () => {
setIsLoading(true);
try {
// here I want to add new document with transaction
await runTransaction(db, async (transaction) => {
let newRecordRef = collection(db, "users", auth.currentUser.uid, "record",);
transaction.set(newRecordRef, {
amount: 1000,
});
});
} catch (err) {
alert(err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
initailizeData();
}, []);
if (isLoading) return <MainFlexLoader />;
return <div className="main"></div>;
}
CodePudding user response:
If you are trying to add a document with a random ID then try:
const newRecordRef = doc(collection(db, "users", auth.currentUser.uid, "record"));
If you want to specify your own ID, then use doc()
itself:
const newRecordRef = doc(db, "users", auth.currentUser.uid, "record", "custom-record-id"));