如何在使用axios发布日期时使用react toast ify promise



//想要在发布时显示微调器,然后使用react toast显示成功/错误消息有可能吗?

axios.post("/orders.json", order)
.then((response) => {
console.log(response.status);
})
.catch((error) => {
console.log(error);
});
import { toast } from "react-toastify";
const promise=axios.post("/orders.json", order)
const res = await toast.promise(promise, {
pending: "Posting",
success: "Posted",
error: "error message",
});

是的,这是可能的。您可以有一个名为isLoading的状态,在提交post请求时可以将其设置为true,并且可以在呈现组件之前检查isLoading,如下所示。

if(isLoading) {
return (<Spinner />)
}

在执行post方法之后,您可以使用toast来显示success/error消息。像下面的

toast.error('Sorry request failed')

toast.success('Request successfull')

但在使用toast之前,您必须将App组件包裹在toast container中,如下所示。

import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App(){
const notify = () => toast("Wow so easy!");
return (
<div>
<button onClick={notify}>Notify!</button>
<ToastContainer />
</div>
);
}

这将解决您的问题。

import React, { useEffect, useState } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
toast.configure({
position: toast.POSITION.BOTTOM_RIGHT
});
export default function App() {
const [state, setState] = useState({
loading: true,
dataArray: []
});
const myRequest = async () => {
try {
const request = await axios.get(`/generic_data/search_skills`);
const { error, msg, data } = request.data;
if (error) throw new Error(msg);
setState({ ...state, loading: false, dataArray: data });
toast.success("All good, we have the data");
} catch (e) {
toast.error("Upps, someting went wrong");
}
};

useEffect(()=>{
myRequest()
},[])
if (state.loading) {
return "Loading data from server.. this will take long time...";
}
return <div>The request has ended. We have the data</div>;
}

相关内容

  • 没有找到相关文章

最新更新