2

I have created a small react app that you can type in a title of book and the author name, and it displays the list under below the form, also it stores in firebase database. If you want to delete it you can delete it frontend, however I have trouble with deleting it in my firebase database because I'm not sure how to dynamically refer the doc id. If I provide the id in the code, it's able to delete this particular id, but the user can't provide the id at frontend. Hoping someone help me out, thanks!

import React, {useContext} from 'react'
import {BookContext} from '../contexts/BookContext'
import firebase from '../config/fbConfig'

const BookDetails = ({bookProp}) => {
    const {actionDispatch} = useContext(BookContext)

    const handleOnClick = () => {
        actionDispatch({type: "REMOVE_BOOK", id: bookProp.id})


        firebase.firestore().collection('books').doc(id).delete()
        .then(()=>{console.log("successfully deleted! ")})
        .catch((error)=>{ console.log("Error removing document:", error)})
    }
    return(
        <div>
            {
                <li onClick={handleOnClick}>
                    <div className="title">{bookProp.title}</div>
                    <div className="author">{bookProp.author}</div>
                </li>
            }
        </div>
    )
    }

export default BookDetails
3
  • Without knowing the ID, there is nothing you can do to delete a document. You will need to make sure any IDs are available to your code. Commented Jun 8, 2020 at 18:16
  • Could you suggest how I should refer the correct firebase doc id in my react code? Commented Jun 8, 2020 at 18:34
  • 1
    When you query for the document, you get the object that has a data() property holding the data of your query and an id property which gives you the uid assigned by firebase for that document. If you posted your query to get the document, I'd be able to show you how to get the uid.
    – user12463073
    Commented Jun 8, 2020 at 20:15

1 Answer 1

1

If you have access to the book name and that same name is stored in the book document in a name field, you can use a where query to get the reference to the book document and delete it.

let bookName = "War And Peace";

firebase.firestore().collection("books").where("name", "==", bookName).get()
.then(querySnapshot => {
    querySnapshot.docs[0].ref.delete();
});

querySnapshot.docs[0].ref.delete(); statement gets the first (and likely the only) book that matches the name query and deletes it.

The other way is to get the id and store it when you get the book document like Vaibhav Joshi said.

5
  • It sounds great but it throws this error message 'TypeError: Cannot read property 'ref' of undefined'. The ideal is deleting from the ID field. I was able to retrieve the exact ID when I adding the book title and the author by: firebase.firestore().collection('books').add({ title: {title}, author: {author}, }) .then(function(docRef){ console.log("document ID:", docRef.id); }) .catch(function(error){ console.error("Error: ", error) }) } but don't know how connect it to delete part .. Commented Jun 9, 2020 at 18:51
  • You are getting 'TypeError" because your query is not matching with the name field of any documents. Remember that the book name for your query must match 100% with the name field of the stored book document. That means if there is any difference in cases, any extra white spaces or symbols, your query will not match and you'll get "Cannot read property 'ref' of undefined". You can also chain another 'where' query with the query to match the author of the books in case there are multiple books with the same name, but that means author's name must match 100% also.
    – Akbar E K
    Commented Jun 9, 2020 at 19:52
  • By getting id when you are creating document, you can only use that id in that session unless you store it somewhere, and I assume this is not what you want. To solve your problem, I need more use case details like how are you getting the details of the book, are you getting all documents under a collection like "books" at once or a collection for a specific user and displaying it under that user? How are you storing the list of books in the client side?
    – Akbar E K
    Commented Jun 9, 2020 at 20:00
  • I created a components folder and adding books and author put in BookForm.jsx and deleting book and author in BookDetails.jsx file. I put it up in my github repository, you can check it out and appreciate your feedback. github.com/jthinlay/reactapp_bookslist/tree/master/src Commented Jun 9, 2020 at 21:04
  • I am not a React developer but I did take a look at your code. Where do you retrieve the documents from Firestore? At the repo, you seem to be using localStorage for storing the docs. Why not also save the firebase generated id that you get when adding to firestore along with the id generated by uuid package if you want that also. When getting documents from firestore, also store the generated id got from querySnapshot along with title and author name in bookState maybe as an array of objects and transfer the id of each doc to handleOnClick function on BookDetail.jsx and delete it from there
    – Akbar E K
    Commented Jun 10, 2020 at 0:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.