I want to delete a specific data from the MUI Datagrid
. Which each data on the Datagrid
is specified by an ID that is incremented every time there is a new data on the database through this code:
const [userData, setUserData] = useState([]); // holds the data from the database
<DataGrid
rows={userData.map((user, index) => { // the rows are the data from the database
return { ...user, id: index + 1 }; // add ID each row
})}
columns={userColumns.concat(actionColumn)}
pageSize={5}
rowsPerPageOptions={[5]}
components={{ Toolbar: GridToolbar }}
/>
The columns are separated in an array of objects:
export const userColumns = [
{
field: "id",
headerName: "ID",
width: 100,
},
{
field: "name",
headerName: "Name",
width: 150,
},
{
field: "number",
headerName: "Number",
width: 120,
},
];
This is the actionColumn
that concatenates the View
, Edit
, and Delete
button to the userColumns
const actionColumn = [
{
field: "action",
headerName: "Action",
width: 200,
renderCell: (params) => {
return (
<>
<div className="cellAction">
<Link to={"/users/" + params.row.id}>
<button className="viewButton">View</button>
</Link>
<button className="deleteButton" onClick={() => handleDelete(params.row.id)}>
Delete
</button>
<Link to={"/users/" + params.row.id}>
<button className="editButton"> Edit</button>
</Link>
</div>
</>
);
},
},
];
I started to work first on handling the delete function. Because I knew if the delete
function would work, then I can get the idea of getting a specific ID for the edit
and view
. However, my delete function seems not working as expected to delete a specific data on the database and on the datagrid itself.
This is what I've tried on the handleDelete
function. I can verify that each data has their own id
by logging it out. But, when I log out the userRef
that suppose holds the users
database attached by its id
, it returns an object like this:
const handleDelete = (id) => {
console.log(id); // display the id
if (window.confirm("Are you sure you want to delete this user?")) {
const userRef = ref(db, `/users/${id}`);
console.log(userRef); // supposed to display the specified user
console.log(`/users/${id}`)
remove(userRef) // delete the specified data on database
.then(() => {
setUserData(userData.filter((user) => user.id !== id)); // delete specified data on datagrid
toast.success("User deleted successfully");
})
.catch((error) => {
toast.error(error.message);
});
}
};
Logging out the users/${id}
shows users/1
. It shows the name of the database and the ID from the specified by the datagrid. But, my users database only have unique ID's generated by the firebase. Although, I assume this would still work as I didn't encounter any problems when using HTML tables. Here's an example of my users database below.
Quite new in react, comments and suggestions are appreciated.