Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react-toastify promise in axios

// how can I use the promise of toastify like I want to show spinner while fetching data then message success or failed

// but I am getting error in bellow code

const fetch = () => {
    axios
      .get("https://restcountries.com/v2/name/india")
      .then((res) => {
        toast.promise({
          pending:"pending",
          success:"success",
          error:"rejected"
        } )
        console.log(res);
      })
      .catch((err) => {
        toast.error("🦄 failed", {
          position: "top-center",
          autoClose: 2000,
          hideProgressBar: true,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined
        });
      });
  };
like image 632
Mohsin Ghazi Avatar asked Sep 02 '25 03:09

Mohsin Ghazi


1 Answers

If you are not using promise. Use toast.loading. (DOCS: https://fkhadra.github.io/react-toastify/promise/#toastloading)

const getData = () => {
 const id = toast.loading("Please wait...")
 axios.get(`some-url`)
   .then(res => { 
      toast.update(id, {render: "All is good", type: "success", isLoading: false});
 }).catch(err => {
        toast.update(id, {render: "Something went wrong", type: "error", isLoading: false });
   });
}

If it is not working then store toast id in useRef and then it will work.

like image 185
SkCODE Avatar answered Sep 04 '25 17:09

SkCODE