I have a list of users in a react-table based table component. The last column in the list shows a delete button. When the delete button is clicked, the user is deleted from the database. How can we re render the table to exclude the deleted user row. A simple page refresh is working fine but that is not the desired functionality.
Table column definition:
{
Header: 'Manage User',
accessor:'userid',
Cell: (value) => {
return (
<div>
<UserDeleteButton userId={value}></UserDeleteButton>
</div>
)
}
}
import React from 'react' import axios from 'axios';
function UserDeleteButton(props) {
const handleDelete = (userId) => {
const jwt = localStorage.getItem('token');
axios
.delete('http://localhost:2000/api/user/' + userId)
.then(() => {
console.log('User deleted');
})
.catch((err) => {
console.log(err);
});
}
return (
<button
onClick={ () => handleDelete(props.userId) }
>
delete
</button>
)
}
export default UserDeleteButton
I tried to use useContext but it is somehow not working for me. The issue is in the hierarchy i.e.
Table Component ---> List of columns ---> Delete Button
I was unable to access Table Component from delete button.
If you define the user state and delete function in the table component and then transfer them to the delete button as a prop, I hope your problem will be solved. I have prepared a rough code below.
import React, { useState } from "react";
import axios from "axios";
export const TableComponent = () => {
const [user, setUser] = useState(null);
const handleDelete = (userId) => {
const jwt = localStorage.getItem("token");
axios
.delete(`http://localhost:2000/api/user/${userId}`)
.then((res) => {
setUser(res.data);
console.log("User deleted");
})
.catch((err) => {
console.error(err);
});
};
const columns = React.useMemo(
() => [
{
Header: "Manage User",
accessor: "userid",
Cell: (value) => {
return (
<div>
<UserDeleteButton
handleDelete={handleDelete}
userId={value}
></UserDeleteButton>
</div>
);
}
}
],
[]
);
return (
user && (
<table>
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
)
);
};
export const UserDeleteButton = ({ handleDelete, userId }) => {
return <button onClick={() => handleDelete(userId)}>delete</button>;
};