I’m encountering an issue with my React application where the state (deleteSuccess) is not updating after a successful deletion operation.
I have a function handleDeleteSubmit that is triggered when a user deletes an item. Inside this function, I make an API call to delete the item. Upon successful deletion (data.error is falsy), I set deleteSuccess state to true. However, even though the deletion is successful, deleteSuccess remains false.
const handleDeleteSubmit = async () => {
if (!accessToken) {
return;
}
try {
const response = await fetch(
apiPath.newsletterApi.deleteNewsLetter(newsletter.location.content_id),
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
const data = await response.json();
if (!data.error) {
console.log("deleted successful:", data);
setDeleteSuccess(true);
let cp = currentNewsletters!.filter(
(news) => news.location.content_id !== newsletter.location.content_id
);
setCurrentNewsletters!(cp);
handleDeleteClose();
} else {
setDeleteError(true);
console.error("Failed to delete:", data);
}
} catch (error) {
setDeleteError(true);
console.error("Error deleting:", error);
}
};
Despite setting deleteSuccess to true, it still logs false. currentNewsletter is just array of data from props.
Any assistance in resolving this issue would be greatly appreciated. Thank you!
code works fine if i comment out this part,
setDeleteSuccess(true);
let cp = currentNewsletters!.filter(
(news) => news.location.content_id !== newsletter.location.content_id
);
setCurrentNewsletters!(cp);
like this,
if (!data.error) {
console.log("deleted successful:", data);
// let cp = currentTemplate!.filter(
// (temp) => temp.location.content_id !== template.location.content_id
// );
// setCurrentTemplate!(cp);
// Perform any actions after successful update
setDeleteSuccess(true);
console.log(deleteSuccess);
handleDeleteClose();
Athar Ishrak Mahir is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.