我想在firebase/firestore中创建一个新的文档,在react中firebase的runTransaction函数中。但是我不知道如何在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>;
}
1条答案
按热度按时间oknwwptz1#
如果您尝试使用随机ID添加文档,请尝试:
如果要指定自己的ID,则使用
doc()
本身: