skip to Main Content

I was trying to make a "AddFolderButton" in a modal of my project so what I wanted was that after adding i click on the button it should update the name and userId in the firebase cloud.
But It shows Error as:
Error adding folder to Firestore: Function collection() cannot be called with an empty path.

Below is my firebase.js

import firebase from "firebase/compat/app"
import "firebase/compat/auth"
import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';

const app = firebase.initializeApp({
    //creds
})


export const db = getFirestore(app);

export const database = {
  folders: collection(db, 'folders'),
  files: collection(db, 'files'),
  formatDoc: (doc) => ({ id: doc.id, ...doc.data() }),
  getCurrentTimestamp: serverTimestamp(),
};

export const storage = getStorage(app);
export const auth = app.auth()
export default app

import React, { useState } from "react";
import { Button, Modal, Form } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFolderPlus } from "@fortawesome/free-solid-svg-icons";
import { database, db } from "../../firebase";
import { useAuth } from "../../contexts/AuthContext";
import {
    getFirestore,
    collection,
    getDocs,
    addDoc,
} from "firebase/firestore";

export default function AddFolderButton({ currentFolder }) {
    const [open, setOpen] = useState(false);
    const [name, setName] = useState("");
    const { currentUser } = useAuth();

    function openModal() {
        setOpen(true);
    }

    function closeModal() {
        setOpen(false);
    }

    async function handleSubmit(e) {
        e.preventDefault();

        try {
            
            console.log("Database folders:", database.folders);
            const folderRef = await addDoc(collection(database.folders), {
                name: name,                
                userId: currentUser.uid,
                createdAt: database.getCurrentTimestamp(),
            });

            console.log(folderRef.id);
            setName("");
            closeModal();
        } catch (error) {
            console.error("Error adding folder to Firestore:", error.message);
        }
    }

    return (
        <>
            <Button onClick={openModal} variant="outline-success" size="sm">
                <FontAwesomeIcon icon={faFolderPlus} />
            </Button>
            <Modal show={open} onHide={closeModal}>
                <Form onSubmit={handleSubmit}>
                    <Modal.Body>
                        <Form.Group>
                            <Form.Label>Folder Name</Form.Label>
                            <Form.Control
                                type="text"
                                required
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                            />
                        </Form.Group>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="secondary" onClick={closeModal}>
                            Close
                        </Button>
                        <Button variant="success" type="submit">
                            Add Folder
                        </Button>
                    </Modal.Footer>
                </Form>
            </Modal>
        </>
    );
}

Above is my AddFolderButton.js

At first the userId was being updated in the firebase but now the same error consoles out

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to a very insightful comment of Guruprasad and an answer by Greg I found out the answer is that When using the addDoc function, you don't need to pass the collection function again for the collection reference. The addDoc function expects a reference to a collection, and database.folders is already a reference to the "folders" collection.

    Here's the corrected handleSubmit function in your AddFolderButton component:

     const folderRef = await addDoc(database.folders, {
                name: name,
                userId: currentUser.uid,
                
            });
    

  2. It would be helpful if you had let us know which call to collection() the error is coming from.

    That said, I suspect it is coming from:

    collection(database.folders)
    

    because collection() takes 2 parameters but you are only providing it with one. You need to provide it with a Firestore object, typically the one you get from getFirestore()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search