I want to show a toast using react-toastify package after succesfully deleting the data object. But the toast function is not working properly here.
import { ToastContainer, toast } from "react-toastify"
function RecipeRow({ recipe, recipes, setRecipes }) {
const { id, title, image_link } = recipe
const handleDeleteRecipe = (id) => {
const proceedToDelete = window.confirm("Are you sure to delete the recipe?")
if (proceedToDelete) {
setRecipes(recipes.filter(r => r.id !== id))
fetch(`http://localhost:3000/recipes/${id}`, {
method: "DELETE",
headers: {
"content-type": "application/json"
},
}).then(res => res.json())
.then(() => {
toast.success("Recipe deleted!")
alert("recipe deleted")
})
} else {
return 0;
}
}
return <>
<ToastContainer autoClose={1000}></ToastContainer>
<tr>
<td>
<div className="flex items-center gap-3">
<div className="avatar">
<div className="mask mask-squircle w-12 h-12">
<img src={image_link} alt="Avatar Tailwind CSS Component" />
</div>
</div>
</div>
</td>
<td>
{title}
</td>
<td>
<button className="btn btn-info text-white">Edit</button>
</td>
<td>
<button onClick={() => handleDeleteRecipe(id)} className="btn btn-error text-white">Delete</button>
<button onClick={() => {
const yes = window.confirm("yehnn")
if (yes) {
const showToast = () => {
toast.success("taosjjjjjj")
}
showToast()
}
}}>Sho Toast</button>
</td>
</tr>
</>
}
export default RecipeRow
I tried to show toast in the showToast() function, that was working perfectly. I also checked the function more than once.
2
Answers
You won’t need any nested
then
function where you don’t use the response data. Try thisI’ve wrapped the
fetch
intotry/catch
for error handling, this will give nice user experienceIf you are using react
<ToastContainer autoClose={1000}></ToastContainer>
warp the App componenet with thisToastContainer
or otherwise