I'm completely new to React and I'm trying to use the React Hooks. I have a functional based component and I'm using the useState and useEffect to get users from my database and display them in a table.
Now, I also have a delete button for each row of my table. When I click on the delete button, I execute a delete function which deletes the data from my database. This works well. However, the table is not updated unless I refresh the whole page completely.
How can I update (re-render) my users table once the delete is done.
Below is a snippet of my code:
const [users, listUsers] = React.useState([]);
React.useEffect(() => {
axios
.get(GET_URL)
.then(res => {
console.log(res.data);
listUsers(res.data);
})
.catch(err => console.log(err));
}, []);
const deleteUser = async id => {
await fetch(DELETE_URL, {
//JSon message
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user_id: id
})
})
.then(response => response.text())
.then(responseJson => {
console.log(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
alert('User Deleted.');
};
You are not updating your list of users state once deletion You have update your list of users state. You can do this by:
const deleteUser = async id => {
await fetch(DELETE_URL, {
//JSon message
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
user_id: id
})
})
.then(response => response.text())
.then(responseJson => {
console.log(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
const usersUpdated = users.filter(p => p.id !== id); //Filter your list of users and remove the one for the specific id
listUsers(usersUpdated); //This updates your state
alert('User Deleted.');
};
;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With