antd#notification JavaScript Examples
The following examples show how to use
antd#notification.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js From the-eye-knows-the-garbage with MIT License | 7 votes |
dealError = (error, FormRef, hide, type) => {
if (error.data && error.data instanceof Object && 'fields_errors' in error.data) {
fieldsLevelErrorHandle(error.data, FormRef);
} else if (error.data && error.data instanceof Object && 'non_field_errors' in error.data) {
notification.error({
message: '温馨提示',
description: `${error.data.non_field_errors}`,
});
} else {
notification.error({
message: '温馨提示',
description: `服务器异常,请重试`,
});
}
hide();
message.error(`${type}失败`);
return false;
}
Example #2
Source File: index.js From acy-dex-interface with MIT License | 6 votes |
helperToast = {
success: content => {
notification.open({
message: <div style={{"color": "#c3c5cb"}}>Submitted</div>,
description: content,
style: {
radius: "10px",
border: "1px solid #2c2f36",
background: "#29292c",
color: "#c3c5cb",
},
onClose: async () => {},
});
// toast.dismiss();
// toast.success(content);
},
error: content => {
notification.open({
message: <div style={{"color": "#c3c5cb"}}>Failed</div>,
description: content,
style: {
radius: "10px",
border: "1px solid #2c2f36",
background: "#29292c",
color: "#c3c5cb",
},
onClose: async () => {},
});
// toast.dismiss();
// toast.error(content);
}
}
Example #3
Source File: request.js From vpp with MIT License | 6 votes |
errorHandler = error => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
} else if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
return response;
}
Example #4
Source File: UploadProgress.js From video-journal-for-teams-fe with MIT License | 6 votes |
function UploadProgress({ isUploading, uploadProgress }) {
function openUploadStartNotification() {
notification.open({
message: "Upload Started!",
description:
"You can continue using the app like normal while the upload happens in the background. However, do not refresh or close the app until it completes!",
icon: <Icon type="loading" style={{ fontSize: 24 }} spin />,
duration: 8,
key: "upload-start",
});
}
function openUploadFinishNotification() {
notification["success"]({
message: "Upload Complete!",
description: "Video upload has finished successfully.",
});
}
function closeUploadStartNotification() {
notification.close("upload-start");
}
useEffect(() => {
if (isUploading && uploadProgress === 0) {
openUploadStartNotification();
}
if (uploadProgress === 100) {
openUploadFinishNotification();
closeUploadStartNotification();
}
}, [uploadProgress, isUploading]);
return <></>;
}
Example #5
Source File: index.js From QiskitFlow with Apache License 2.0 | 6 votes |
getExperiments(query = "") {
axios.get(`http://localhost:8000/experiments/`, {
params: {
query: query
}
}).then((response) => {
this.setState({
...this.state, experiments: response.data
})
}).catch((err) => {
notification.open({ message: 'Error', description: err.message, style: { backgroundColor: 'red' } });
});
}
Example #6
Source File: Notification.js From dexwebapp with Apache License 2.0 | 6 votes |
export function notifySuccess(message, theme, duration) {
trackEvent(message);
notification.success({
message: message,
closeIcon: closeIcon(theme),
icon: <FontAwesomeIcon icon={faCheckCircle} />,
duration: duration || 3,
top: topPosition,
style: {
color: theme.green,
background: theme.notificationBackground,
},
});
}
Example #7
Source File: request.js From online-test-platform with Apache License 2.0 | 6 votes |
errorHandler = error => {
const { response = {} } = error;
const errortext = codeMessage[response.status] || response.statusText;
const { status, url } = response;
if (status === 401) {
notification.error({
message: '未登录或登录已过期,请重新登录。',
});
// @HACK
/* eslint-disable no-underscore-dangle */
window.g_app._store.dispatch({
type: 'login/logout',
});
return;
}
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errortext,
});
// environment should not be used
if (status === 403) {
router.push('/exception/403');
return;
}
if (status <= 504 && status >= 500) {
router.push('/exception/500');
return;
}
if (status >= 404 && status < 422) {
router.push('/exception/404');
}
}
Example #8
Source File: request.js From react-drag with MIT License | 6 votes |
// respone interceptors
service.interceptors.response.use(
response => {
// 200 maybe has error
const { data = {} } = response;
if (data.code === 0) {
return data;
}
return data;
},
err => {
const { response = {} } = err;
if (err.response) {
if (err.response.status === 401) {
// 返回 401 清除token信息并跳转到登录页面
router.push({
pathname: '/login',
});
notification.error({
message: '请求错误',
description: '用户没有权限(令牌、用户名、密码错误),请重新登陆',
});
}
}
return Promise.resolve(response.data);
},
);
Example #9
Source File: request.js From spring-boot-plus-admin-react with Apache License 2.0 | 6 votes |
errorHandler = error => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
if (response.status === 401) {
localStorage.clear();
router.push('/user/login')
}
} else if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
return response;
}
Example #10
Source File: index.js From gobench with Apache License 2.0 | 6 votes |
ACL = ({
user: { role },
redirect = false,
defaultRedirect = '/auth/404',
roles = [],
children,
}) => {
useEffect(() => {
const authorized = roles.includes(role)
// if user not equal needed role and if component is a page - make redirect to needed route
if (!authorized && redirect) {
const url = typeof redirect === 'boolean' ? defaultRedirect : redirect
notification.error({
message: 'Unauthorized Access',
description: (
<div>
You have no rights to access this page.
<br />
Redirected to "{url}"
</div>
),
})
history.push(url)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const authorized = roles.includes(role)
const AuthorizedChildren = () => {
// if user not authorized return null to component
if (!authorized) {
return null
}
// if access is successful render children
return <Fragment>{children}</Fragment>
}
return AuthorizedChildren()
}
Example #11
Source File: request.js From egoshop with Apache License 2.0 | 6 votes |
errorHandler = error => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
} else if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
return response;
}
Example #12
Source File: handle-error.js From mixbox with GNU General Public License v3.0 | 6 votes |
export default function handleError({ error, errorTip }) {
const { status } = error?.response || {};
// 如果是未登录问题,不显示错误提示,直接跳转到登录页面
if (status === 401) return toLogin();
// 用户设置false,关闭提示,不显示错误信息
if (errorTip === false) return;
const description = getErrorTip({ error, errorTip });
notification.error({
message: '失败',
description,
duration: 2,
});
}
Example #13
Source File: index.js From discern with BSD 3-Clause "New" or "Revised" License | 6 votes |
customNotification(){
const key = Date.now()
notification.open({
message: 'Notification Title',
description: 'A function will be be called after the notification is closed (automatically after the "duration" time of manually).',
key,
btn:<Button type="primary" onClick={() => notification.close(key)}>Confirm</Button>
})
}
Example #14
Source File: errorHandler.js From erp-crm with MIT License | 6 votes |
errorHandler = (error) => {
const { response } = error;
if (response && response.status) {
const message = response.data && response.data.message;
const errorText = message || codeMessage[response.status];
const { status } = response;
notification.config({
duration: 10,
});
notification.error({
message: `Request error ${status}`,
description: errorText,
});
if (response.data && response.data.jwtExpired) {
history.push('/logout');
}
return response.data;
} else {
notification.config({
duration: 5,
});
notification.error({
message: 'No internet connection',
description: 'Cannot connect to the server, Check your internet network',
});
return {
success: false,
result: null,
message: 'Cannot connect to the server, Check your internet network',
};
}
}
Example #15
Source File: successHandler.js From starter-antd-admin-crud-auth-mern with MIT License | 6 votes |
successHandler = (response, typeNotification = {}) => {
if (!response.data.result) {
response = {
...response,
status: 404,
url: null,
data: {
success: false,
result: null,
},
};
}
const { data } = response;
if (data.success === false) {
const message = data && data.message;
const errorText = message || codeMessage[response.status];
const { status } = response;
notification.config({
duration: 20,
});
notification.error({
message: `Request error ${status}`,
description: errorText,
});
} else {
const message = data && data.message;
const successText = message || codeMessage[response.status];
const { status } = response;
// notification.config({
// duration: 20,
// });
// notification.success({
// message: `Request success`,
// description: successText,
// });
}
return data;
}
Example #16
Source File: request.js From aircon with GNU General Public License v3.0 | 6 votes |
request.interceptors.response.use(
async (data) => {
return data;
},
(error) => {
if (error.response && error.response.status) {
const { response } = error;
const errorText = codeMessage[response.status] || response.statusText;
notification.error({
message: `请求错误: ${response.status}`,
description: errorText,
});
if (response.status === 401) {
console.log(401);
setTimeout(() => history.push('/login'), 2000);
}
return Promise.reject(error.response.data);
} else {
notification.error({
message: `请求错误: ${error.message}`,
});
return Promise.reject(error);
}
}
);
Example #17
Source File: request.js From youdidao-unmanned-shop with MIT License | 6 votes |
checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const errortext = codeMessage[response.status] || response.statusText;
notification.error({
message: `请求错误 ${response.status}: ${response.url}`,
description: errortext,
});
const error = new Error(errortext);
error.name = response.status;
error.response = response;
throw error;
}
Example #18
Source File: Notification.js From loopring-pay with Apache License 2.0 | 6 votes |
export function notifySuccess(message, theme, duration) {
notification.success({
message: message,
closeIcon: closeIcon(theme),
icon: <FontAwesomeIcon icon={faCheckCircle} />,
duration: duration || 3,
top: topPosition,
style: {
color: theme.green,
background: theme.notificationBackground,
},
});
}
Example #19
Source File: saga.js From bank-client with MIT License | 6 votes |
export function* setUserData({ snippets }) {
const { accessToken } = yield select(makeSelectToken());
const newData = yield select(makeSelectNewData());
const isCollapsedSidebar = yield select(makeSelectIsCollapsedSidebar());
const requestURL = api.users();
const requestParameters = {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(newData),
};
const style = { width: 400, marginLeft: isCollapsedSidebar ? 80 : 250 };
const placement = 'bottomLeft';
try {
const userData = yield call(request, requestURL, requestParameters);
yield put(setUserDataSuccessAction(userData));
notification.success({
message: snippets.success.title,
description: snippets.success.description,
style,
placement,
});
} catch (error) {
yield put(setUserDataIncorrectAction(error));
}
}
Example #20
Source File: App.js From quick_redis_blog with MIT License | 6 votes |
// left width = 300(minSize)+15(line)+
componentDidMount() {
window.addEventListener("resize", this.resize.bind(this));
this.resize();
HeartbeatService.start();
CheckUpdateService.start();
notification.open({
message: intl.get("notification.support.host.key.tree.title"),
description: intl.get(
"notification.support.host.key.tree.description"
),
onClick: () => {},
});
}
Example #21
Source File: Detail.js From ant-back with MIT License | 6 votes |
componentDidMount() {
const {
query: { id },
} = this.props.location;
if (id === undefined) return;
request(`/empty-item/article/detail`, {
method: 'POST',
data: {
id
},
}).then(res => {
if (res.code === 'SUCCESS') {
this.setState({
current: res.data,
});
} else {
notification.error({
message: res.code,
description: res.msg,
});
}
this.setState({
loading: false,
});
});
}
Example #22
Source File: request.js From the-eye-knows-the-garbage with MIT License | 6 votes |
errorHandler = error => {
const { response, data } = error;
if (response.status === 500) {
notification.error({
message: '温馨提示',
description: `服务器发生异常,请重试`,
});
}
else if (response.status === 403 && data instanceof Object && 'none_fields_errors' in data) {
console.log("请登录,cookie可能已过期,或还未登录")
// notification.error({
// message: '温馨提示',
// description: `身份认证过期,请重新登录!`,
// });
}
else if (data && data instanceof Object && 'fields_errors' in data) {
throw error;
}
else if (response) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
} else if (!response) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
return response;
}
Example #23
Source File: basic.jsx From virtuoso-design-system with MIT License | 6 votes |
openNotification = () => {
notification.open({
message: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
onClick: () => {
console.log('Notification Clicked!');
},
});
}
Example #24
Source File: global.js From acy-dex-interface with MIT License | 5 votes |
// Pop up a prompt on the page asking the user if they want to use the latest version
window.addEventListener('sw.updated', e => {
const reloadSW = async () => {
// Check if there is sw whose state is waiting in ServiceWorkerRegistration
// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
const worker = e.detail && e.detail.waiting;
if (!worker) {
return Promise.resolve();
}
// Send skip-waiting event to waiting SW with MessageChannel
await new Promise((resolve, reject) => {
const channel = new MessageChannel();
channel.port1.onmessage = event => {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
});
// Refresh current page to use the updated HTML and other assets after SW has skiped waiting
window.location.reload(true);
return true;
};
const key = `open${Date.now()}`;
const btn = (
<Button
type="primary"
onClick={() => {
notification.close(key);
reloadSW();
}}
>
{formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
</Button>
);
notification.open({
message: formatMessage({ id: 'app.pwa.serviceworker.updated' }),
description: formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
btn,
key,
onClose: async () => {},
});
});
Example #25
Source File: ReportWorkspace.jsx From node-project-manager with Apache License 2.0 | 5 votes |
ReportWorkspace = ({ component: Component, report,...rest }) => {
const openNotification = result => {
// TODO :
switch (result.type){
case "success":
notification.success({
message: `${result.message}`,
placement:'bottomRight'
});
break;
default:
notification.error({
message: result.message,
placement:'bottomRight'
});
}
};
return (
<Route
{...rest}
render={(props) =>
<div className="reportWorkspace">
<Component {...props} />
<hr/>
<div className="buttonEra">
<Button
className="buttonReport"
ghost={false}
type="default"
icon={<FilePdfOutlined />}
onClick={async ()=>{
const pdfBlob = await Http.postPDF(report,report.reportUrl);
if (pdfBlob.message){
openNotification(pdfBlob);
}else{
const url = URL.createObjectURL(pdfBlob);
window.open(url,'_blank');
}
}}
>Generar Informe</Button>
</div>
</div>
}
/>
);
}
Example #26
Source File: Transactor.js From moonshot with MIT License | 5 votes |
// this should probably just be renamed to "notifier"
// it is basically just a wrapper around BlockNative's wonderful Notify.js
// https://docs.blocknative.com/notify
export default function Transactor(provider, gasPrice, etherscan) {
if (typeof provider !== "undefined") {
// eslint-disable-next-line consistent-return
return async tx => {
const signer = provider.getSigner();
const network = await provider.getNetwork();
console.log("network", network);
const options = {
dappId: BLOCKNATIVE_DAPPID, // GET YOUR OWN KEY AT https://account.blocknative.com
system: "ethereum",
networkId: network.chainId,
// darkMode: Boolean, // (default: false)
transactionHandler: txInformation => {
console.log("HANDLE TX", txInformation);
},
};
const notify = Notify(options);
let etherscanNetwork = "";
if (network.name && network.chainId > 1) {
etherscanNetwork = network.name + ".";
}
let etherscanTxUrl = "https://" + etherscanNetwork + "etherscan.io/tx/";
if (network.chainId === 100) {
etherscanTxUrl = "https://blockscout.com/poa/xdai/tx/";
}
try {
let result;
if (tx instanceof Promise) {
console.log("AWAITING TX", tx);
result = await tx;
} else {
if (!tx.gasPrice) {
tx.gasPrice = gasPrice || parseUnits("4.1", "gwei");
}
if (!tx.gasLimit) {
tx.gasLimit = hexlify(120000);
}
console.log("RUNNING TX", tx);
result = await signer.sendTransaction(tx);
}
console.log("RESULT:", result);
// console.log("Notify", notify);
// if it is a valid Notify.js network, use that, if not, just send a default notification
if ([1, 3, 4, 5, 42, 100].indexOf(network.chainId) >= 0) {
const { emitter } = notify.hash(result.hash);
emitter.on("all", transaction => {
return {
onclick: () => window.open((etherscan || etherscanTxUrl) + transaction.hash),
};
});
} else {
notification.info({
message: "Local Transaction Sent",
description: result.hash,
placement: "bottomRight",
});
}
return result;
} catch (e) {
console.log(e);
console.log("Transaction Error:", e.message);
notification.error({
message: "Transaction Error",
description: e.message,
});
}
};
}
}
Example #27
Source File: MarketStreamPanel.js From websocket-demo with MIT License | 5 votes |
function MarketStreamPanel({ actions, selectedStream }) {
const [type, setType] = useState('');
const onSelectChange = value => {
setType(value);
actions.removeAllSelectedStream();
};
const onClickSubscribe = env => {
if (selectedStream.codes.length === 0) {
return notification['error']({
message: i18n.t('label.error'),
description: i18n.t('message.marketStreamInput')
});
}
actions.subscribeMarketStream(env);
};
return (
<>
<Title level={5}>{i18n.t('label.marketStream')}</Title>
<Form className="market-stream">
<Form.Item label="Source">
<Select placeholder={i18n.t('message.selectStream')} onChange={onSelectChange}>
{allMarketStreams.map(streamType => (
<Option key={streamType.type} value={streamType.type}>
{i18n.t(`label.${streamType.type}`)}
</Option>
))}
</Select>
</Form.Item>
<Form.Item label="Streams">
<Dropdown overlay={type && <StreamMenu actions={actions} type={type} />}>
<span>
{i18n.t('message.selectStream')} <DownOutlined />
</span>
</Dropdown>
</Form.Item>
{selectedStream.codes.length > 0 && (
<Form.Item>
<TagDisplay actions={actions} tags={selectedStream.codes} />
</Form.Item>
)}
</Form>
<Button type="default" style={{ margin: '5px' }} onClick={() => onClickSubscribe(TESTNET)}>
{i18n.t('label.testSubscribe')}
</Button>
<Button type="primary" style={{ margin: '5px' }} onClick={() => onClickSubscribe(PROD)}>
{i18n.t('label.prodSubscribe')}
</Button>
</>
);
}
Example #28
Source File: openNotification.js From bonded-stablecoin-ui with MIT License | 5 votes |
openNotification = (message, description) => {
const args = {
message,
duration: 10,
};
notification.open(args);
}
Example #29
Source File: axios.js From AgileTC with Apache License 2.0 | 5 votes |
export default function request(url, opt) {
// 调用 axios api,统一拦截
const options = {}
options.method = opt !== undefined ? opt.method : 'get'
if (opt) {
if (opt.body) {
options.data = typeof opt.body === 'string' ? JSON.parse(opt.body) : opt.body
}
// if (opt.headers) options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
if (opt.params !== undefined) {
url += '?'
for (let key in opt.params) {
if (opt.params[key] !== undefined && opt.params[key] !== '') {
url = url + key + '=' + opt.params[key] + '&'
}
}
url = url.substring(0, url.length - 1)
}
}
return axios({
url,
...options,
})
.then(response => {
// >>>>>>>>>>>>>> 请求成功 <<<<<<<<<<<<<<
// console.log(`【${opt.method} ${opt.url}】请求成功,响应数据:`, response)
// 打印业务错误提示
// if (response.data && response.data.code != '0000') {
// message.error(response.data.message)
// }
// eslint-disable-next-line
if (response.data.code === 401 || response.code === 401) {
let loginPath = `${response.data.data.login_url}?app_id=${response.data.data.app_id}`
let pagePath = encodeURIComponent(window.location.href)
const redirectURL = `${loginPath}&version=1.0&jumpto=${pagePath}`
window.location.href = redirectURL
return Promise.reject(new Error('服务不可用,请联系管理员'))
}
// >>>>>>>>>>>>>> 当前未登录 <<<<<<<<<<<<<<
if (response.data.code === 99993 || response.code === 99993) {
const redirectURL = `/login`
window.location.href = redirectURL
return Promise.reject(new Error('服务不可用,请联系管理员'))
}
return { ...response.data }
})
.catch(error => {
// >>>>>>>>>>>>>> 请求失败 <<<<<<<<<<<<<<
// 请求配置发生的错误
if (!error.response) {
// eslint-disable-next-line
return console.log('Error', error.message);
}
// 响应时状态码处理
const status = error.response.status
const errortext = codeMessage[status] || error.response.statusText
notification.error({
message: `请求错误 ${status}`,
description: errortext,
})
return { code: status, message: errortext }
})
}