Skip to content
Advertisement

React Firebase deleting the wrong document id

I’ve been trying to make a delete operation on a firebase database using Reactjs. I’ve got a bug with my function grabbing the wrong id from firebase.

I have a button that calls a handleOpen function which opens a Modal.

Modal operations:

JavaScript

I’ve got a button that calls a handleDelete function which grabs the document id reference and deletes the document reference.

handleDelete function:

JavaScript

The Problem

From what I’ve been watching the handleDelete function grabs the last id from the mapped array of posts, it doesn’t pass the id of the current document to the modal.

The problem only happens when I pass the function inside the modal. When I pass the function outside of the modal it works just fine.

The Objective

Grabbing document id, passing it to the modal and deleting the respective document.

Here’s the full code:

JavaScript

Advertisement

Answer

You could define a state variable that keeps tracks of the currently editing ID:

JavaScript

Then edit your handleOpen and handleClose functions:

JavaScript

In the handleDelete function, if an ID is selected, delete that one:

JavaScript

Finally, you will need to update the handleOpen method in the JSX by adding the id parameter:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement