Home > Enterprise >  React/Firebase. Why I can't delete element from my Firestore Database?
React/Firebase. Why I can't delete element from my Firestore Database?

Time:07-30

When I adding an item to the cart, it also gets into the database, but when I click on the delete button, the item is removed from the cart, but not from the database. What am I doing wrong?

This is a function that adds a product on click. (if necessary):

  const handleClick = async(item) => {
    const newItem = { ...item, id: v4() }
    await addDoc(collection(db, 'cart_products'), {
      id: newItem.id,
      image: newItem.image,
      name: newItem.name,
      priceTotal: newItem.priceTotal,
      category: newItem.category
    })
    setList([...list, newItem])
    console.log(newItem)
  }

This is a delete function:

    const deleteProduct = async(id) => {
        await deleteDoc(doc(db, 'cart_products', id))
        setList((list) => list.filter((product) => id !== product.id))
    }


    const products = list.map((product) => {
        return <CartItem product={product} key={product.id} deleteProduct={deleteProduct}/>
    })

This is a delete button

     <button className="btn bin" onClick={() => {deleteProduct(product.id)}}>
       <img src={bin} alt="bin" className='bin'/>
     </button>

CodePudding user response:

You're using the addDoc method, which is used for generating it's own id for documents, while in the meantime you're generating your own (different) id on the client-side with uuid.v4

Just change your add (handleClick) method to, so your firestore id matches the one you're creating with your uuid.v4 call.

setDoc(doc(db, 'cart_products', newItem.id), { 
 // ... data here
})

and it will work.

Alternatively you can just use the generated id from the addDoc method and take out the dependency on uuid entirely. (the addDoc call returns a Promise<DocumentReference> which contains the readonly property id you can access)

Note: Your previous documents contain corrupted data (property id does not match the document.id), and will either need to be removed or fixed via a migration function

  • Related