Hello I was trying to delete a specific document from my collection because I though I knew the code (I was reading this:
- This is how it looks updated in the firestore
- This is how it looks in the table:
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.
CodePudding user response:
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.
CodePudding user response:
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>
CodePudding user response:
I suggest when adding items to firebase to use the add() function, this way firebase automatically generates a unique id for your doc.