react-toastify#toast JavaScript Examples
The following examples show how to use
react-toastify#toast.
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: _Helpers.js From acy-dex-interface with MIT License | 6 votes |
helperToast = {
success: content => {
toast.dismiss();
toast.success(content);
},
error: content => {
toast.dismiss();
toast.error(content);
}
}
Example #2
Source File: project.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 6 votes |
uploadProjectThumbnailAction = (formData) => async (dispatch) => {
const config = {
onUploadProgress: (progressEvent) => {
dispatch({
type: actionTypes.PROJECT_THUMBNAIL_PROGRESS,
payload: {
progress: `Uploaded progress: ${Math.round((progressEvent.loaded / progressEvent.total) * 100)}%`,
},
});
},
};
const centralizedState = store.getState();
toast.info('Uploading image...', {
position: 'top-center',
hideProgressBar: false,
icon: '',
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
autoClose: 30000,
});
const {
organization: { activeOrganization },
} = centralizedState;
const { thumbUrl } = await projectService.upload(formData, config, activeOrganization.id);
toast.dismiss();
dispatch({
type: actionTypes.UPLOAD_PROJECT_THUMBNAIL,
payload: { thumbUrl },
});
return thumbUrl;
}
Example #3
Source File: MainPage.js From viade_en2b with MIT License | 6 votes |
MainPage = () => {
cache.default.loadFriends();
groupcache.default.getGroups(() => {});
const [showDropzone, setShowDropzone] = useState(false);
const getZone = () => {
return <DropzonePage showUpload={() => showZone()} />;
};
const showZone = () => {
routecache.default.getSelected().then((selected) => {
if (selected !== "") {
setShowDropzone(!showDropzone);
} else {
toast.error("No Route Selected", {
draggable: true,
position: toast.POSITION.TOP_CENTER,
});
}
});
};
return (
<div className="App" id="outer-container">
<BurgerMenu pageWrapId="page-wrap" container="outer-container" />
<main className="main" id="page-wrap">
<FloatingButton showUpload={() => showZone()} />
<div>{showDropzone ? getZone() : null}</div>
<MapContainer />
</main>
<UserDropdown />
</div>
);
}
Example #4
Source File: App.js From viade_es2a with BSD 2-Clause "Simplified" License | 6 votes |
App = () => (
<Suspense fallback={<Loader />}>
<Fragment>
<Routes />
<Toaster
{...{
autoClose: 5000,
position: toast.POSITION.TOP_CENTER,
newestOnTop: true,
closeOnClick: true,
pauseOnVisibilityChange: true,
draggable: true,
className: 'solid-toaster-container',
toastClassName: 'solid-toaster',
bodyClassName: 'solid-toaster-body',
transition: Slide
}}
/>
</Fragment>
</Suspense>
)
Example #5
Source File: ReactNotification.js From expriments_with_react with MIT License | 6 votes |
ReactNotificationComponent = ({ title, body }) => {
let hideNotif = title === "";
if (!hideNotif) {
toast.info(<Display />);
}
function Display() {
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
);
}
return (
<ToastContainer
autoClose={3000}
hideProgressBar
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss={false}
draggable
pauseOnHover={false}
/>
);
}
Example #6
Source File: Login.js From Music-Hoster-FrontEnd-Using-React with MIT License | 6 votes |
async login() {
await fetch("/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(this.state),
}).then((result) => {
if(result.status !== 200){
toast("Incorrect Username or Password");
}else{
result.json().then((res) => {
localStorage.setItem("jwt", res.jwt);
this.props.history.push("/uploadmusic");
window.location.reload();
});
}
});
// if (
// localStorage.getItem("jwt") !== null &&
// localStorage.getItem("jwt") !== "undefined"
// ) {
// this.props.history.push("/uploadmusic");
// window.location.reload();
// } else {
// this.props.history.push("/login");
// toast("Incorrect Username or Password");
// }
}
Example #7
Source File: ReleaseUpdate.js From SaraAlert with Apache License 2.0 | 6 votes |
submit() {
this.setState(
{
showReleaseUpdateModal: false,
},
() => {
axios.defaults.headers.common['X-CSRF-Token'] = this.props.authenticity_token;
axios
.post(window.BASE_PATH + '/admin/email', {
comment: this.state.comment,
})
.then(() => {
toast.success('Sent email to all users.', {
position: toast.POSITION.TOP_CENTER,
});
})
.catch(() => {
toast.error('Failed to send email to all users.', {
autoClose: 2000,
position: toast.POSITION.TOP_CENTER,
});
});
}
);
}
Example #8
Source File: index.js From HexactaLabs-NetCore_React-Initial with Apache License 2.0 | 6 votes |
export function create(provider) {
return function(dispatch) {
dispatch(setLoading(true));
return api
.post(`/provider/`, provider)
.then(response => {
toast.success("El proveedor se creó con éxito");
dispatch(success(response.data.data));
dispatch(setLoading(false));
return dispatch(goBack());
})
.catch(error => {
apiErrorToast(error);
return dispatch(setLoading(false));
});
};
}
Example #9
Source File: App.js From saasgear with MIT License | 6 votes |
function App() {
useDocumentHeader({ title: 'SaaSgear' });
const { error } = useSelector((state) => state.user);
useEffect(() => {
if (error) {
toast.error(error);
}
}, [error]);
return (
<ApolloProvider client={client}>
<BrowserRouter>
<GlobalStyle />
<GlobalLoading />
<ToastContainer />
<Switch>
<Route path="/verify-email" component={VerifyEmail} />
<Route path="/social/:provider/callback" component={Social} />
<Route
path="/teams/invitation/:invitationToken"
component={AcceptInvitation}
/>
<PublicRoute path="/auth" component={Auth} />
<PrivateRoute render={(props) => <AdminLayout {...props} />} />
<Redirect from="*" to="/" />
</Switch>
</BrowserRouter>
</ApolloProvider>
);
}
Example #10
Source File: index.js From HexactaLabs-NetCore_React-Level2 with Apache License 2.0 | 6 votes |
export function create(productType) {
return function(dispatch) {
dispatch(setLoading(true));
return api
.post(`/producttype/`, productType)
.then(response => {
if (!response.data.success) {
var error = {response: {data: {Message: response.data.message}}};
return handleError(dispatch, error);
}
dispatch(success(response.data.data));
dispatch(setLoading(false));
toast.success("El nuevo tipo se creó con exito");
return dispatch(replace("/product-type"));
})
.catch(error => {
return handleError(dispatch, error);
});
};
}
Example #11
Source File: httpService.js From React-JS with MIT License | 6 votes |
// Types of requests
// CRUD application -> Create,Read, Update and Delete
// POST Request -> Create resource
// GET Request -> Fetching/Reading the resource
// PUT([
// {'a' :'a'},
// {'b':'b'}
// ]) / PATCH([{'a':'A'}]) -> Updating the resource
// DELETE Request -> Deleteing a resource
//AJAX Example
// function loadDoc() {
// var xhttp = new XMLHttpRequest();
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
// }
// };
// xhttp.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
// xhttp.send();
// }
axios.interceptors.response.use(null, error => {
// console.log("Error log",err);
// console.log(error);
const expectedError = error.response && error.response.status >= 400 && error.response.status<500;
if(expectedError){
toast.error('Expected error occured');
}else{
toast("Unexpected Error");
}
return Promise.reject(error);
});
Example #12
Source File: gapiFrontend.jsx From Athavani with MIT License | 6 votes |
async googleDataSend(){ // this funtion handels the user data on the state and sends it to the backend through axios defined in ../api/index.js
const { history } = this.props;
if(history) {
try {
// console.log("inside google data send"); Use for Debugging
history.push("/signin/Gsignin");
const idToken = this.state.idToken;
const userData = {
idToken
};
// console.log("user Data", userData.idToken) Use for Debugging
const { data } = await api.Gsignin(userData);
console.log(data);
toast.success(data.message);
console.log(data);
localStorage.setItem('token', data.token);
localStorage.setItem('user', JSON.stringify(data.user));
// console.log("it worked!!!"); Use for Debugging
history.push('/');
}catch(error) {
if(error.response) {
toast.error(error.response.data.message);
} else if(error.request) {
toast.error("Server is not Responding!");
// console.log(error.request);
} else {
toast.error(error.message);
// console.log(error.message);
}
}
}
}
Example #13
Source File: helpers.js From ErgoAuctionHouse with MIT License | 6 votes |
export function showMsg(message, isError = false, isWarning = false) {
let status = 'default'
if (isError) status = 'error'
if (isWarning) status = 'warning'
toast(message, {
transition: Slide,
closeButton: true,
autoClose: 5000,
position: 'top-right',
type: status,
});
}
Example #14
Source File: shared-monaco-editor.jsx From codeinterview-frontend with Apache License 2.0 | 6 votes |
componentDidMount() {
this.langService
.getLanguages()
.then(languages => {
this.languages = languages;
})
.catch(err => {
console.error(err);
toast.error(
`Could not load server language data. ${err.message}`
);
})
.finally(() => {
const {
language,
sharedEditorDidMount,
loadTemplate,
} = this.props;
if (this.state.language === 'none') {
this.setState({
language,
loadTemplate,
});
}
sharedEditorDidMount(this);
});
}
Example #15
Source File: auth.js From club-connect with GNU General Public License v3.0 | 6 votes |
loginRedirect = async (router) => {
toast.warn('Please log in before visiting this page.', {
position: 'top-center',
});
await router.push({
pathname: '/login',
query: { returnToPage: router.asPath },
});
}
Example #16
Source File: patient-information.js From OpenSource_ventilator_lungs with GNU General Public License v3.0 | 6 votes |
async handleSubmit(ev) {
ev.preventDefault();
const res = await fetch(`${getApiUrl()}/api/patient_info`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstName: this.state.firstName,
lastName: this.state.lastName,
admittanceDate: this.state.admittanceDate + 'T' + this.state.admittanceTime,
info: this.state.info,
}),
});
const resJson = await res.json();
if (!resJson.result) {
toast.error('Failed to update information!');
} else {
toast.success('Successfully updated!');
}
}
Example #17
Source File: useGetAuditorias.jsx From core-audit with MIT License | 6 votes |
useGetAuditorias = () => {
const dispatch = useDispatch()
const getAuditorias = async () => { // Traer auditorias y la actual
const auditoriasFix = [];
const auditoriasTemp = await firestoreDB.collection("auditorias").get();
console.log({auditoriasTemp})
let auditTemp = {};
auditoriasTemp.forEach(async (snapshot) => {
auditTemp = {
...snapshot.data(),
id: snapshot.id
};
auditoriasFix.push(auditTemp);
if (auditTemp.actual === true) {
dispatch({type: "set", auditoriaActual: auditTemp});
// Traer libros de la auditorias actual
console.log({auditTemp});
}
});
dispatch(({type: "set", auditoriasIglesia: auditoriasFix}));
toast.info("Datos traídos.");
};
return getAuditorias
}
Example #18
Source File: toastError.js From whaticket with MIT License | 6 votes |
toastError = err => {
const errorMsg = err.response?.data?.message || err.response.data.error;
if (errorMsg) {
if (i18n.exists(`backendErrors.${errorMsg}`)) {
toast.error(i18n.t(`backendErrors.${errorMsg}`), {
toastId: errorMsg,
});
} else {
toast.error(errorMsg, {
toastId: errorMsg,
});
}
} else {
toast.error("An error occurred!");
}
}
Example #19
Source File: App.js From code-examples-react with MIT License | 6 votes |
/**
* Is the accessToken ok to use?
* @returns boolean accessTokenIsGood
*/
checkToken() {
if (
!this.state.accessToken ||
this.state.expires === undefined ||
new Date() > this.state.expires
) {
// Need new login. Only clear auth, don't clear the state (leave form contents);
this.clearAuth();
this.setState({ page: 'welcome', working: false });
toast.error('Your login session has ended.\nPlease login again', {
autoClose: 8000,
});
return false;
}
return true;
}
Example #20
Source File: register.js From light-blue-react-template with MIT License | 6 votes |
export function registerUser(payload) {
return (dispatch) => {
if (payload.creds.email.length > 0 && payload.creds.password.length > 0) {
toast.success("You've been registered successfully");
payload.history.push('/login');
} else {
dispatch(registerError('Something was wrong. Try again'));
}
}
}
Example #21
Source File: register.js From sofia-react-template with MIT License | 6 votes |
export function registerUser(payload) {
return (dispatch) => {
if (payload.creds.email.length > 0 && payload.creds.password.length > 0) {
toast.success("You've been registered successfully");
payload.history.push('/login');
} else {
dispatch(registerError("Something was wrong. Try again"));
}
}
}
Example #22
Source File: Masks.js From mailmask with GNU Affero General Public License v3.0 | 6 votes |
Masks = ({ className, me }) => {
const query = useSafeQuery(GetMyMasksQuery, {
variables: {
paging: {
page: 1,
resultsPerPage: 1000000
}
}
})
const [ updateMaskStatus ] = useSafeMutation(UpdateMaskStatusMutation)
const setMaskStatus = useCallback(async (name, enabled) => {
const { error } = await updateMaskStatus({
variables: {
name,
enabled,
}
})
if (error) {
toast.error(`Update error: ${error.message}`)
}
}, [ updateMaskStatus ])
return (
<Container className={className}>
{isSelfHosted() ? null : <StyledBandwidthStatsThisMonth me={me} />}
<QueryResult {...query}>
{({ result }) => <MaskTable {...result} setMaskStatus={setMaskStatus} me={me} />}
</QueryResult>
</Container>
)
}
Example #23
Source File: project.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 5 votes |
createProjectAction = (data) => async (dispatch) => {
const centralizedState = store.getState();
const {
organization: { activeOrganization },
} = centralizedState;
try {
dispatch({ type: actionTypes.CREATE_PROJECT_REQUEST });
toast.info('creating project ...', {
position: 'top-center',
hideProgressBar: false,
icon: '',
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
});
const { project } = await projectService.create(data, activeOrganization.id);
dispatch({
type: actionTypes.CREATE_PROJECT_SUCCESS,
payload: { project },
});
toast.dismiss();
if (project) {
toast.success('New Project Created', {
position: 'top-center',
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
return project;
}
// dispatch(allSidebarProjects());
} catch (e) {
dispatch({ type: actionTypes.CREATE_PROJECT_FAIL });
Swal.fire({
icon: 'error',
title: 'Error',
text: e.message || 'Something went wrong !',
});
}
}
Example #24
Source File: FloatingButton.js From viade_en2b with MIT License | 5 votes |
FloatingButton = (props) => {
let history = useHistory();
const [recording,setRecording] = useState(false);
const startRecording = ()=>{
toast.info("Route recording started", {
draggable: true,
position: toast.POSITION.TOP_CENTER
});
setRecording(true);
RealTimeRoute.default.main()
}
const finishRecording = ()=>{
toast.info("Route recording stopped", {
draggable: true,
position: toast.POSITION.TOP_CENTER
});
setRecording(false);
RealTimeRoute.default.stop();
//props.showSaveRoute();
history.push('/saveroute')
}
return (
<Fab className="mainButton"
event={'click'}
icon={<i className ="fa fa-plus fafab"></i>}
>
<Action className="actionButton" text="Add route"><i className="fa fa-map-pin fafab"></i></Action>
<Action className="actionButton" text="Take Photo" onClick={props.showUpload}><i className="fa fa-camera fafab"></i></Action>
{
recording ? <Action className="actionButton" text="Stop" onClick={() => finishRecording()}><i className="fa fas fa-stop"></i></Action>
:<Action className="actionButton" text="Record" onClick={() => startRecording()}><i className="fa fa-circle"></i></Action>
}
</Fab>
);
}
Example #25
Source File: toaster.js From viade_es2a with BSD 2-Clause "Simplified" License | 5 votes |
errorToaster = (content: String, title: String = null, link: Object) =>
toast(<Toaster {...{ content, title, type: 'error', link }} />, {
autoClose: false,
className: 'solid-toaster toaster-error',
type: 'error'
})
Example #26
Source File: Enrollment.js From SaraAlert with Apache License 2.0 | 5 votes |
submit(_event, groupMember, reenableSubmit) {
window.onbeforeunload = null;
axios.defaults.headers.common['X-CSRF-Token'] = this.props.authenticity_token;
let data = new Object({
patient: this.state.enrollmentState.patient,
propagated_fields: this.state.enrollmentState.propagatedFields,
});
data.patient.primary_telephone = data.patient.primary_telephone
? phoneUtil.format(phoneUtil.parse(data.patient.primary_telephone, 'US'), PNF.E164)
: data.patient.primary_telephone;
data.patient.secondary_telephone = data.patient.secondary_telephone
? phoneUtil.format(phoneUtil.parse(data.patient.secondary_telephone, 'US'), PNF.E164)
: data.patient.secondary_telephone;
const message = this.props.editMode ? 'Monitoree Successfully Updated.' : 'Monitoree Successfully Saved.';
if (this.props.parent_id) {
data['responder_id'] = this.props.parent_id;
}
data['bypass_duplicate'] = false;
axios({
method: this.props.editMode ? 'patch' : 'post',
url: window.BASE_PATH + (this.props.editMode ? '/patients/' + this.props.patient.id : '/patients'),
data: data,
})
.then(response => {
if (response['data']['duplicate']) {
// Duplicate, ask if want to continue with create
this.handleConfirmDuplicate(
data,
groupMember,
message,
reenableSubmit,
'This monitoree appears to be a duplicate of an existing record in the system. Are you sure you want to enroll this monitoree?'
);
} else {
// Success, inform user and redirect to home
toast.success(message, {
onClose: () =>
(location.href = window.BASE_PATH + (groupMember ? '/patients/' + response['data']['id'] + '/group' : '/patients/' + response['data']['id'])),
});
}
})
.catch(err => {
reportError(err);
});
}
Example #27
Source File: apiErrorToast.js From HexactaLabs-NetCore_React-Initial with Apache License 2.0 | 5 votes |
export function apiErrorToast(error) {
if (error.response) {
toast.error(error.response.data.Message);
} else if (error.request) {
toast.error("Server not responding");
}
}
Example #28
Source File: ResetPassword.jsx From saasgear with MIT License | 5 votes |
function ResetPassword() {
useDocumentHeader({ title: 'Reset password' });
const query = getQueryParam();
const history = useHistory();
const token = query.get('token');
const { register, handleSubmit, errors } = useForm({
resolver: yupResolver(ResetPasswordSchema),
});
const [loginMutation, { error, loading }] = useMutation(resetPasswordQuery);
useEffect(() => {
if (!token) {
history.push('/auth/signin');
}
}, [token]);
async function onSubmit({ password, passwordConfirmation }) {
const { data } = await loginMutation({
variables: {
token,
password,
confirmPassword: passwordConfirmation,
},
});
if (data?.resetPassword) {
toast.success('Change password successfully!');
history.push('/auth/signin');
}
}
return (
<ForgotPasswordWrapper>
<Overlay />
<ForgotPasswordContainer>
<ResetPasswordForm
onSubmit={handleSubmit(onSubmit)}
register={register}
errors={errors}
apiError={error?.message}
isSubmiting={loading}
/>
<SquareIconTop>
<img src={squareRadiusTop} alt="" />
</SquareIconTop>
<SmallSquareBottom>
<img src={squareRadiusTopPrimary} alt="" />
</SmallSquareBottom>
<SmallSquareTop>
<img src={squareRadiusTopPrimarySmall} alt="" />
</SmallSquareTop>
<SmallSquareGrid>
<img src={squareGrid} alt="" />
</SmallSquareGrid>
<SquareIconBottom>
<img src={squareRadiusTopBig} alt="" />
</SquareIconBottom>
<CircleIcon>
<img src={circleSmall} alt="" />
</CircleIcon>
</ForgotPasswordContainer>
</ForgotPasswordWrapper>
);
}
Example #29
Source File: Home.js From ReactJS-Projects with MIT License | 5 votes |
Home = () => {
const context = useContext(UserContext)
const [query, setQuery] = useState("")
const [user, setUser] = useState(null)
const fetchDetails = async () => {
try {
const { data } = await Axios.get(`https://api.github.com/users/${query}`)
setUser(data)
console.log(data)
} catch (err) {
toast("Unable to locate the user", {
type: "error"
})
}
}
if (!context.user?.uid) {
return <Navigate to="/signin" />
}
return (
<Container>
<Row className=" mt-3">
<Col md="5">
<InputGroup>
<Input
type="text"
value={query}
placeholder="Please provide the username"
onChange={e => setQuery(e.target.value)}
/>
<InputGroupAddon addonType="append">
<Button onClick={fetchDetails} color="primary">Fetch User</Button>
</InputGroupAddon>
</InputGroup>
{user ?
<UserCard user={user} /> :
null
}
</Col>
<Col md="7">
{user ? <Details apiUrl={user.repos_url} /> : null}
</Col>
</Row>
</Container>
);
}