我正在尝试将我在 fetch 调用中获得的 data.message 传递给 toastify 承诺的成功。我知道我可以在那里做一个 toast.success ,但我特别想使用 toastify Promise 并想看看如何在 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
});
来自
react-toastify
文档:
// In your promise:
- resolve();
+ resolve(data.message)
// Toast
toast.promise(
myPromise,
{
success: {
render({data}){ // The data you resolve
return data
},
},
}
)
另一种方法是将消息存储在变量中。
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!"
},
...
)
您可以使用toast更新方法,这样代码的可读性将会提高。
const id = toast.loading("wait...");
const { apiSuccess, apiError }: any = await ApiCall();
if (apiSuccess) {
toast.update(id, {
render: "All is good",
type: "success",
isLoading: false
});
} else if (apiError) {
toast.update(id, {
render: apiError.response.data.message,
type: "error",
isLoading: false
});
}