skip to Main Content

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


  1. You won’t need any nested then function where you don’t use the response data. Try this

    const handleDeleteRecipe = async id => {
        const proceedToDelete = window.confirm('Are you sure to delete the recipe?');
        if (proceedToDelete) {
            setRecipes(recipes.filter(r => r.id !== id));
            
            try{
                await fetch(`http://localhost:3000/recipes/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'content-type': 'application/json'
                    }
                })
                toast.success('Recipe deleted!');
            }catch(e){
                toast.success('Something went wrong while deleting!');
            }
    
        } else {
            return false;
        }
    };
    

    I’ve wrapped the fetch into try/catch for error handling, this will give nice user experience

    Login or Signup to reply.
  2. If you are using react <ToastContainer autoClose={1000}></ToastContainer> warp the App componenet with this ToastContainer

    or otherwise

    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(prevRecipes => prevRecipes.filter(r => r.id !== id));
    
      try {
        const response = await fetch(`http://localhost:3000/recipes/${id}`, {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json"
          }
        });
    
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
    
        const result = await response.json();
        console.log(result);
    
        toast.success("Recipe deleted!");
        alert("Recipe deleted");
      } catch (error) {
        console.error('Error deleting recipe:', error);   
        toast.error("Failed to delete recipe.");
      }            
            } else {
                return 0;
            }
        }
    
        return
            <ToastContainer autoClose={1000}>
            <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>
        </ToastContainer>
    
    }
    export default RecipeRow
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search