Muhammad Abbas
Muhammad Abbas

Reputation: 47

Firebase (Firestore) not adding data and not throwing error

I am creating an application with basic crud operations to manage inventory. I am using firestore for this project. 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?

Here's my code for 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) Console Network Tab

Here's the code for 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();

Upvotes: 0

Views: 1770

Answers (1)

Guillaume Dionisi
Guillaume Dionisi

Reputation: 121

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. 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.

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!

Upvotes: 2

Related Questions