[英]How I can use react-toastify promise while posting date using axios
[英]How to use react-toastify promise in axios
// 我如何使用 toastify 的承諾,就像我想在獲取數據時顯示微調器然后消息成功或失敗
// 但我在下面的代碼中遇到錯誤
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
});
});
};
根據 toast API https://fkhadra.github.io/react-toastify/promise/語法應該是
const myPromise = fetchData();
toast.promise(myPromise, {
loading: 'Loading',
success: 'Got the data',
error: 'Error when fetching',
})
可以在https://codesandbox.io/s/twilight-bash-jzs24y?file=/src/App.js上找到的示例
export default function App() {
const myPromise = new Promise((resolve) =>
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => setTimeout(() => resolve(json), 3000))
// setTimeout just for the example , cause it will load quickly without it .
);
useEffect(() => {
toast.promise(myPromise, {
pending: "Promise is pending",
success: "Promise Loaded",
error: "error"
});
}, []);
return (
<div className="App">
<ToastContainer />
</div>
);
}
如果你沒有使用承諾。 使用toast.loading
。 (文檔: 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 });
});
}
如果它不起作用,則將 toast id 存儲在 useRef 中,然后它將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.