Firebase deleteDoc()不会从数据库中删除,也不会捕获任何错误

inkz8wg9  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在尝试使用代码中的删除按钮从数据库中删除类别。虽然单击删除按钮后在控制台上收到成功消息,但该类别并未从数据库中删除。我已检查是否具有从数据库中删除类别所需的权限和访问权限,并已验证是否将正确的类别ID传递给删除函数。

import {
  addDoc,
  collection,
  deleteDoc,
  doc,
  getDocs,
} from "firebase/firestore";
import React, { useEffect, useState } from "react";
import { db } from "../Config";
import { v4 as uuidv4 } from "uuid";
const Category = () => {
  const [categoryList, setCategoryList] = useState([]);
  const [category, setCategory] = useState();
  // add category to firebase
  const CategoryCollection = collection(db, "Category");

  const addCategory = async () => {
    try {
      const docRef = await addDoc(CategoryCollection, {
        id: uuidv4(),
        name: category,
      });
      console.log("Document written with ID: ", docRef.id);
    } catch (e) {
      console.error("Error adding document: ", e);
    }
  };
  //  fetch all category from firebase
  // const fetchCategory = async () => {
  //   const Data = await getDocs(CategoryCollection);
  //   Data.map((doc) => {
  //     setCategoryList((prev) => [...prev, doc.data()]);
  //   });
  // };
  useEffect(() => {
    const fetchCategory = async () => {
      try {
        const Data = await getDocs(CategoryCollection);
        const categories = [];
        Data.forEach((doc) => {
          categories.push(doc.data());
        });
        setCategoryList(categories);
      } catch (e) {
        console.error("Error fetching categories: ", e);
      }
    };
    fetchCategory();
  }, []);

  //  delete one category by id from firebase when click an button
  const deleteCategory = async (id) => {
    try {
      await deleteDoc(doc(db, "Category", id));
      console.log("Document successfully deleted!");
    } catch (e) {
      console.error("Error removing document: ", e);
    }
  };

  return (
    <div>
      <div className="grid  place-content-center ">
        <p className="text-center uppercase font-bold my-8">Category</p>
        <div className="border-2 rounded-2xl p-5 flex flex-col items-center">
          <div className="flex items-end ">
            <Input
              label="category"
              onChange={(e) => {
                setCategory(e.target.value);
              }}
            />
            <button
              className="bg-blue-400 text-white rounded-2xl px-4 py-2 h-10 mx-4"
              onClick={() => addCategory()}
            >
              add
            </button>
          </div>

          <section className="container columns-3 mt-6">
            <div>
              {categoryList.map((cat) => (
                <p
                  className="border-2 rounded-2xl p-5  h-8  flex items-center justify-between mb-2 "
                  key={cat.id}
                >
                  <p>{cat.name}</p>
                  <button
                    className=" text-white bg-black rounded-2xl  border h-8 w-8  mx-4"
                    onClick={() => {
                      deleteCategory(cat.id);
                    }}
                  >
                    X
                  </button>
                </p>
              ))}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
};

export default Category;
yquaqz18

yquaqz181#

您的代码依赖于在每个文档的data()中有一个id字段,我猜情况可能并非如此。
如果你想使用每个文档自动拥有的id元数据字段,你需要确保该值也在你的categoryList中结束,如下所示:

Data.forEach((doc) => {
  categories.push(...doc.data(), id: doc.id);
});

相关问题