简体   繁体   English

Firebase (Firestore) 不添加数据也不抛出错误

[英]Firebase (Firestore) not adding data and not throwing error

I am creating an application with basic crud operations to manage inventory.我正在创建一个具有基本 crud 操作的应用程序来管理库存。 I am using firestore for this project.我正在为此项目使用 firestore。 However, the data is not being added to my collection nor collection is being created.但是,数据没有添加到我的收藏中,也没有创建收藏。 I could not find the error because seemingly everything is fine and no error is generated.我找不到错误,因为似乎一切都很好并且没有生成错误。 Even responses from Firebase website in.networks tab were all 200. What am I doing wrong?甚至来自 Firebase 网站 in.networks 标签的回复都是 200。我做错了什么?

Here's my code for AddItem.js:这是我的 AddItem.js 代码:

import React, { useState } from "react";
import { Alert, Button, Form } from "react-bootstrap";
import { database } from "../../../Firebase";
import { useAuth } from "../../context/AuthContext";

export default function AddItem() {
  const [name, setName] = useState("");
  const [vendor, setVendor] = useState("");
  const [quantity, setQuantity] = useState("");
  const [loading, setLoading] = useState(false);
  const [sessionMessage, setSessionMessage] = useState(false);

  const { currentUser } = useAuth();

  const sub = (e) => {
    e.preventDefault();
    setLoading(true);

    //   Create a new item in database
    database
      .collection("items")
      .add({
        name: name,
        quantity: quantity,
        vendor: vendor,
        addedBy: currentUser.email,
      })
      .then((docRef) => {
        console.log("Document written with ID: ", docRef.id);
      })
      .catch((error) => {
        console.error("Error adding document: ", error);
      });

    setLoading(false);
    setSessionMessage("Created a new Item!");
    setName("");
    setQuantity("");
    setVendor("");
  };

  return (
    <>
      {sessionMessage && <Alert variant="info">{sessionMessage}</Alert>}
      <Form
        onSubmit={(event) => {
          sub(event);
        }}
      >
        <Form.Group>
          <Form.Label>Item Name</Form.Label>
          <Form.Control
            type="text"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </Form.Group>

        <Form.Group>
          <Form.Label>Quantity</Form.Label>
          <Form.Control
            type="number"
            required
            value={quantity}
            onChange={(e) => setQuantity(e.target.value)}
          />
        </Form.Group>

        <Form.Group>
          <Form.Label>Vendor Name</Form.Label>
          <Form.Control
            type="text"
            required
            value={vendor}
            onChange={(e) => setVendor(e.target.value)}
          />
        </Form.Group>
        <br />
        <Button
          disabled={loading}
          variant="primary"
          type="submit"
          className="w-100"
        >
          Add Item
        </Button>
      </Form>
    </>
  );
}

Infinite queries in.networks tab (Update) .networks 选项卡中的无限查询(更新) 控制台网络选项卡

Here's the code for Firebase.js这是 Firebase.js 的代码

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSENGER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
});

export const auth = app.auth();
export default app;
export const database = app.firestore();

Not sure what the problem is exactly, but here's a hint:不确定问题到底是什么,但这里有一个提示:

Your sub method is not async , though the add method from Firestore returns a Promise .您的sub方法不是async ,尽管 Firestore 的add方法返回Promise You are not "awaiting" the result from your database query to run the lines afterwards.您不是在“等待”数据库查询的结果以在之后运行这些行。 That means your loader will disappear, the form will reset and the success message will be displayed before the object has been added.这意味着您的加载程序将消失,表单将重置并且成功消息将在添加 object 之前显示。

Try changing it to this:尝试将其更改为:

const sub = async (e) => {
    e.preventDefault();
    setLoading(true);

    //   Create a new item in database
    const docRef = await database
      .collection("items")
      .add({
        name: name,
        quantity: quantity,
        vendor: vendor,
        addedBy: currentUser.email,
      });

    console.log("Document written with ID: ", docRef.id);

    setLoading(false);
    setSessionMessage("Created a new Item!");
    setName("");
    setQuantity("");
    setVendor("");
  };

Hopefully you will get more insights on what goes wrong then!希望你能对出了什么问题有更多的见解!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM