Reputation: 35
I am using "MDB" data table from "mdbootstrap" in my react project so I want to delete row after on click button. the user deleted from the server but the frontend still showing the row with the user I was Deleted But after I refresh the page the row is gone . the delete request sent successfully to the server. here is my code: set state does not solve the problem :
class Users extends Component {
notify = () => toast.warn(" User deleted Successfully !");
state = {
users: [],
tableRows: [],
}
async componentDidMount() {
await axios.get('http://localhost:3000/admin/users', {
headers: {
'x-access-token': localStorage.getItem("token")
}
}
)
.then(response => response.data)
.then(data => {
this.setState({ users: data })
})
.then(() => {
this.setState({ tableRows: this.getusers() })
});
}
getusers = () => {
let users = this.state.users.map((user) => {
return (
{
id: user._id,
name: user.name,
cin: user.cin,
delete: <MDBIcon
icon='trash'
className='red-text'
size='1x'
style={{ cursor: 'pointer' }}
onClick={() => this.handeldelete(user._id)}
/>,
add: <Analys userId={user._id} />
}
)
});
return users;
}
handeldelete = async userId => {
await axios.delete("http://localhost:3000/admin/users/" + userId, {
headers: {
'x-access-token': localStorage.getItem("token")
}
});
const tableRow = this.state.tableRows;
const userIndex = tableRow.findIndex(user => user.userId === userId); //It doesn't work
tableRow.filter(1, userIndex);
this.setState({ tableRows: tableRow });
};
render() {
const data = {
columns: [
{
label: 'USER ID',
field: 'id',
sort: 'asc',
width: 150
},
{
label: 'Name',
field: 'name',
sort: 'asc',
width: 270
},
{
label: 'CIN',
field: 'cin',
sort: 'asc',
width: 200
},
{
label: 'Delet',
field: 'delete',
sort: 'asc',
width: 200
},
{
label: 'ADD ANALYS',
field: 'add',
sort: 'asc',
width: 200
},
],
rows: this.state.tableRows,
};
return (
<div>
<MDBDataTableV5 hover data={data} filter='name' proSelect searchTop searchBottom={false} />
<ToastContainer />
</div>
);
}
}
Upvotes: 0
Views: 2068
Reputation: 544
const [employees, setEmployees] = useState([])
const removeData = (id) => {
let url = https://jsonplaceholder.typicode.com/users/${id}
axios.delete(url).then(res => {
const del = employees.filter(employee => id !== employee.id)
setEmployees(del)
})
}
Upvotes: 0
Reputation: 1719
Your delete function need a little rework. When you do the async axios delete call, you'll need to remove the data from your local state too.
handeldelete = async userId => {
await axios.delete("http://localhost:3000/admin/users/" + userId, {
headers: {
'x-access-token': localStorage.getItem("token")
}
});
this.setState((prev) => ({
tableRows: prev.tableRows.filter(
(row) => row.id !== userId
)
}));
};
I reproduce your app with fake data right here : https://codesandbox.io/s/goofy-herschel-vwe2s?file=/src/App.js
Upvotes: 2