React JS - Firestore: How to delete a document inside a collection

Viewed 204

Hello I was trying to delete a specific document from my collection because I though I knew the code (I was reading this: Delete data from Cloud Firestore ) to delete a document with specific ID inside a collection, clearly I was wrong GLADLY it was a test collection.

So my question is how to delete a document from a collection using a specific ID First of all this is how I store data inside my collection:

const register = (e) => {
        e.preventDefault();

        const docId = `${descripcion}`;
        const docRef = db.collection('productosAIB').doc(docId);

        docRef.get().then((doc) => {

            if (doc.exists) 
            {
                window.alert("Ya existe ese producto")
            }
            else {
                docRef.set({
                    descripcion: descripcion,
                    grado: grado,
                    precio: precio,
                    cantidad: cantidad,
                    id: docRef.id
            }).then((r) => {
                window.alert("Producto agregado")
            })}
    })
}

So I make a variable called docID that will grab a description that the user can send through an input then I make sure the docs created will be the doc.id then I send all the information to the database and this is the final result:

  • All the data is inserted by the user first

enter image description here

  • This is how it looks updated in the firestore

enter image description here

  • This is how it looks in the table:

enter image description here

Now I made a function called deleteProduct which is the one that is suppose to delete the document and not the whole collection:

const deleteProduct = (producto) => {
        db.collection("productosAIB").doc(producto).delete();
    }

And this is where the table is being render/print and where the function is being called (Note: The function is on "" (quotes) because I do not want the function to run because it will delete the document I just created)

<tbody>
                {productos.map((productos, index) => (
                        <tr key={productos.id || index}>
                        <td>
                            <input className = "agregarAIB_cantidad"
                            onChange = {(e) => {changeCantidad(productos.descripcion, e.target.valueAsNumber)}}
                            type = 'number'
                            pattern = "[0-9]*"
                            required
                            value = {productos.cantidad}
                            />
                        </td>

                        <td>{productos.grado}</td>

                        <td >
                        {productos.descripcion}
                        </td>

                        <td >$
                        <input className = "agregarAIB_precio"
                            onChange = {(e) => {changePrecio(productos.descripcion, e.target.valueAsNumber)}}
                            type = 'number'
                            pattern = "[0-9]*"
                            required
                            value = {productos.precio}
                            />
                        </td>

                        <th>
                            <button onClick = "{deleteProduct(productos.descripcion)}"/> <-- This is the function
                        </th>
                        </tr>
                     ))
                     }
                </tbody>

Now what was weird (which is why I came here to ask) is that I did not even click the button and it ran the function (which is why I have it on quotes for now), it is because is on a map or something ? because it doesn't make sense to me that it runs without clicking the button it says "OnClick" for a reason.

Anyways any tips, documentations, help is welcome, let me know if require full code.

3 Answers

Change the button element to this

<button onClick = { ()=>{deleteProduct(productos.descripcion)}}/>

What you are doing now invokes the function immediately. Instead you have to pass an instance of the function.

you can do it this way:

    your doc_id: docID = 123abc (anything);
    
    const handleDelete = async () => {
    try{
    await firebase.firestore().collection("collectionName").doc(docID).delete();
    console.log("record deleted");
    // update your state or anything you want to do after deletion
    }
    catch(error){
    console.log(error.message);
    }
}

//your Button:
<Button onClick={()=>{deleteProduct(productos.descripcion)}}>Delete</Button>

I suggest when adding items to firebase to use the add() function, this way firebase automatically generates a unique id for your doc.

Related