如何在react(firebase)中为runTransaction创建新的文档引用?

f0ofjuux  于 2022-11-17  发布在  React
关注(0)|答案(1)|浏览(107)

我想在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>;
}
oknwwptz

oknwwptz1#

如果您尝试使用随机ID添加文档,请尝试:

const newRecordRef = doc(collection(db, "users", auth.currentUser.uid, "record"));

如果要指定自己的ID,则使用doc()本身:

const newRecordRef = doc(db, "users", auth.currentUser.uid, "record", "custom-record-id"));

相关问题