'How to update the content when is deleted
I simply can't get this thing working for me. I have an item that is being deleted on a backend side but it is not rendering immediately on a front. You need to refresh the whole page to make it work. I saw similar questions asked here, but I couldn't make it work on my example.
So here in my component I'm getting the data from backend:
const AdminMessages = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(
`http://localhost:5000/contact/message/`
);
setData(response.data);
setError(null);
} catch (err) {
setError(err.message);
setData(null);
} finally {
setLoading(false);
}
};
getData();
}, []);
return (
{data.map((item) => (
<h3 className="bold-text">{item.title}</h3>
<div
name="trash-outline"
id="approve-icon"
onClick={() => dispatch(deleteContactMessage(item._id))}
></div>
))}
)
);
};
And here is my controller for delete:
export const deleteContactMessage = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send("No post with that id");
await ContactMessage.findByIdAndRemove(id);
res.json({ message: "Post deleted successfully" });
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
