I am trying to delete all my data in API using a "delete all" button with event handler, where it calls an async function to set my items
to an empty array. While doing that, I would like it to update my page every time I click the button and update the page data without refreshing the page using useEffect
. However, the page updates only when I refresh the page(behave like componentDidMount()
). After some research, I realized that adding items
in the useEffect
hook in the array argument would tell DOM to rerender, only when items
is changed. However, after some debugging, I realized handleDelete
function is called every time I refresh the page, which is something I don't want it to do. I have searched and found a lot of question regarding this issue, but no answers can solve my problem. Is there a way to get around it? I would like the page to update only when I click the delete button and no more that that.
Here is my code
export default function Dashboard() {
const [items, setItems] = useState([]);
const fetchList = async () => {
await axios.get("/api/items").then((res) => {
setItems(res.data.reverse());
});
};
const handleDelete = () =>{
axios.delete("/api/items").then((res)=>{
setItems(res.data);
console.log('-- res.data --', res.data)
})
}
useEffect(() => {
fetchList();
console.log("fetchList activate")
}, []);
return (
<div className={styles.dashboard_container}>
<button className={styles.delete_all} onClick={handleDelete}>Delete All</button>
{items.map((item) => {
const { _id, name, phone, numberofpeople, time } = item;
return (
<div className={styles.waitlist_item} key={_id}>
<h4>{name}</h4>
<h5>{phone}</h5>
<h4>{numberofpeople}</h4>
<h5>{moment(time).format("MMM Do, h:mm:ss A ddd")}</h5>
</div>
);
...
Here is the code in my backend router that deals with delete request.
router.delete("/api/items", (req, res) => {
Item.deleteMany({}, (err) => {
if (err) {
res.status(500);
} else {
res.json({ success: true });
}
});
});
CodePudding user response:
Some suggestions regarding backend:
router.delete("/", (req, res) => {
Item.deleteMany({}, (err) => {
if (err) {
response.status(500);
} else {
(res) => res.json({ success: true });
}
});
});
Should be res.status(500)
instead of response.status(500)
Check your route, this one seems to be incorrect, try /itmes
or maybe /api/items
(res) => res.json({ success: true });
this part also seems incorrect, should be:
else {
res.json({ success: true }); // or res.json([])
}
Good luck!)
CodePudding user response:
Your handleDelete in being called when the fetchList add the data into items.
You can do it like this: Create a new state
const [deleteAll, setDeleteAll] = useState(false);
Change your button to:
<button className={styles.delete_all} onClick={() => setDeleteAll(true)}>Delete All</button>
and change your useEffect
useEffect(() => {
handleDelete();
console.log("handleDelete activate")
}, [deleteAll == true])