0

I am trying to pass the data.message that I am getting in the fetch call to the success of toastify promise. I know I can do a toast.success in there but I specifically want to use toastify promise and want to see how I can pass data in promise.

 const myPromise = new Promise((resolve, reject) =>
          fetch(`${baseURL}/accounts/getData`, {
            method: 'POST',
            headers: {
              "Content-Type": "application/json",
              "authorization": `Bearer ${auth?.user?.authToken}`
            },
            body: JSON.stringify(data)
    
          })
            .then(res => res.json())
            .then(data => {
              if (data?.status === 'success' && data?.message) {
                resolve();
              } else {
                throw error;
              }
            })
            .catch(error => {
              reject();
            })
        )
        toast.promise(myPromise, {
          pending: "Loading...",
          success: <Want to show here data.message that I got from API above>,
          error: "Something went wrong. Please try again!"
        },
          {
            position: "top-center",
            autoClose: 5000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true
          });
Sugar Code
  • 25
  • 5

1 Answers1

1

From react-toastify documentiaon:

// In your promise:
 - resolve();
 + resolve(data.message)

// Toast
toast.promise(
    myPromise,
    {
      success: {
        render({data}){ // The data you resolve
          return data
        },
      },
    }
)

Another way would be storing the message in a variable.

let message = null;
const defaultMessage = 'Success!'

const myPromise = new Promise((resolve, reject) =>
  fetch(...)
    .then((res) => res.json())
    .then((data) => {
      if (data?.status === "success" && data?.message) {
        message = data.message;
        resolve();
      }
    ...
    })
    .catch(error => {
      message = null;
      reject()
    })

);

toast.promise(myPromise, {
  pending: "Loading...",
  success: message ?? defaultMessage,
  error: "Something went wrong. Please try again!"
},
...
)
c0m1t
  • 1,089
  • 1
  • 7
  • 16