Clean callback functions (replaced by async/await)

This commit is contained in:
Michael B
2022-01-17 16:11:05 +01:00
committed by GitHub
7 changed files with 146 additions and 113 deletions

View File

@@ -6,36 +6,46 @@ If you want to change the email provider, don't hesitate to create a new api rou
the axios.post here, line 18.
*/
import axios from 'axios';
import axios, { AxiosError } from 'axios';
import { toast } from 'react-toastify';
const sendEmail = (): void => {
const sendEmail = async (): Promise<void> => {
const name = (document.querySelector('#name') as HTMLInputElement).value;
const email = (document.querySelector('#email') as HTMLInputElement).value;
const message = (document.querySelector('#message') as HTMLInputElement)
.value;
interface EmailData {
success: boolean;
message: string;
}
interface ErrorAxios {
data: {
error: string;
success: boolean;
};
}
if (name && email && message) {
axios
.post('/api/sendgrid', { email, name, message })
.then(
(result: {
data: {
success: boolean;
message: string;
};
}) => {
if (result.data.success === true) {
toast.success(result.data.message);
(document.querySelector('#name') as HTMLInputElement).value = '';
(document.querySelector('#email') as HTMLInputElement).value = '';
(document.querySelector('#message') as HTMLInputElement).value = '';
}
}
)
.catch((error) => {
console.log(error);
try {
const mail = await axios.post<EmailData>('/api/sendgrid', {
email,
name,
message,
});
if (mail.data.success === true) {
toast.success(mail.data.message);
(document.querySelector('#name') as HTMLInputElement).value = '';
(document.querySelector('#email') as HTMLInputElement).value = '';
(document.querySelector('#message') as HTMLInputElement).value = '';
}
} catch (error: unknown) {
const errorChecked = error as AxiosError;
const errorMessage = errorChecked.response as ErrorAxios;
toast.error(errorMessage.data.error);
}
} else {
toast.info('Please fill all the fields ', {
position: 'top-center',
@@ -97,7 +107,7 @@ const Contact = (): JSX.Element => {
className="btn btn-primary btn-sm"
onClick={(event) => {
event.preventDefault();
sendEmail();
void sendEmail();
}}>
Submit{' '}
</button>

View File

@@ -3,9 +3,10 @@ This is the form component to register an email adress to your mailing list.
This is just the frontend, and the email will be send to our backend API (/api/mailingList)
*/
import axios, { AxiosError } from 'axios';
import Image from 'next/image';
import Mailing from 'public/landing/mailing.svg';
import axios from 'axios';
import { toast } from 'react-toastify';
import { useState } from 'react';
@@ -14,6 +15,12 @@ const MailingList = (): JSX.Element => {
const [loading, setLoading] = useState(false);
const [valid, setValid] = useState(true);
interface ErrorAxios {
data: {
error: string;
success: boolean;
};
}
const validateEmail = (): void => {
// Regex patern for email validation
const regex =
@@ -21,7 +28,7 @@ const MailingList = (): JSX.Element => {
if (regex.test(mail)) {
// this is a valid email address
subscribe();
void subscribe();
setValid(true);
} else {
// invalid email.
@@ -30,24 +37,28 @@ const MailingList = (): JSX.Element => {
}
};
const subscribe = (): void => {
const subscribe = async (): Promise<void> => {
setLoading(true);
axios
.put('api/mailingList', {
try {
const data = await axios.put('api/mailingList', {
mail,
})
.then((result) => {
if (result.status === 200) {
toast.success(
'Your email has been succesfully added to the mailing list. Welcome 👋'
);
setLoading(false);
}
})
.catch((error) => {
console.log(error);
setLoading(false);
});
if (data.status === 200) {
toast.success('You have been added to our mailing list. Welcome 👋');
setLoading(false);
setMail('');
}
} catch (error: unknown) {
const errorChecked = error as AxiosError;
const errorMessage = errorChecked.response as ErrorAxios;
if (errorMessage.data.error) {
toast.error(errorMessage.data.error);
setLoading(false);
}
}
};
return (
<div className="flex flex-col m-auto my-10 mt-24">

View File

@@ -21,15 +21,20 @@ const Pricing = (): JSX.Element => {
useEffect(() => {
if (user) {
void getSub().then((result) => setSub(result));
void supabase
.from<definitions['subscriptions']>('subscriptions')
.select(`customer_id`)
.eq('id', user.id)
.single()
.then((result) => {
setCustomerId(result.data?.customer_id);
});
const subFunction = async (): Promise<void> => {
const sub = await getSub();
if (sub) {
setSub(sub);
}
const subSupa = await supabase
.from<definitions['subscriptions']>('subscriptions')
.select(`customer_id`)
.eq('id', user.id)
.single();
setCustomerId(subSupa.data?.customer_id);
};
void subFunction();
}
}, [user]);

View File

@@ -24,11 +24,15 @@ const Login = ({ resetPassword, signIn }: LoginProperties): JSX.Element => {
const [forgot, setForgot] = useState(false);
const resetPasswordLogin = async (): Promise<void> => {
await resetPassword(email).then((result: { error: ApiError | null }) => {
if (result.error) {
toast.error(result.error.message);
} else toast.success('Check your email to reset your password!');
});
const result = await resetPassword(email);
if (result.error) {
toast.error(result.error.message);
} else if (result.data) {
toast.success(
'A password reset email has been sent to you, watch your mailbox!'
);
}
};
const login = async (
@@ -37,17 +41,16 @@ const Login = ({ resetPassword, signIn }: LoginProperties): JSX.Element => {
event.preventDefault();
// Handle the login. Go to the homepage if success or display an error.
await signIn({
const result = await signIn({
email,
password,
}).then((result) => {
if (result) {
void router.push('/');
}
if (result.error) {
toast.error(result.error.message);
}
});
if (result.error) {
toast.error(result.error.message);
} else if (result.user) {
void router.push('/');
}
};
return (

View File

@@ -32,21 +32,20 @@ const SignUpPanel = ({
event.preventDefault();
// Handle the login. Go to the homepage if success or display an error.
await signUp({
const result = await signUp({
email,
password,
}).then((result) => {
console.log(result);
if (result.error) {
toast.error(result.error.message);
} else if (result.user?.confirmation_sent_at) {
toast.success(
'A confirmation email has been sent to you, watch your mailbox!'
);
} else if (result.user) {
void router.push('/');
}
});
if (result.error) {
toast.error(result.error.message);
} else if (result.user?.confirmation_sent_at) {
toast.success(
'A confirmation email has been sent to you, watch your mailbox!'
);
} else if (result.user) {
void router.push('/');
}
};
return (

View File

@@ -37,33 +37,30 @@ export default async function handler(
await cors(request, response);
await limiter(request, response);
if (request.method === 'PUT') {
axios
.put(
'https://api.sendgrid.com/v3/marketing/contacts',
{
contacts: [{ email: `${request.body.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_ID],
const result = await axios.put(
'https://api.sendgrid.com/v3/marketing/contacts',
{
contacts: [{ email: `${request.body.mail}` }],
list_ids: [process.env.SENDGRID_MAILING_ID],
},
{
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${process.env.SENDGRID_SECRET || ''}`,
},
{
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${process.env.SENDGRID_SECRET || ''}`,
},
}
)
.then((result) => {
console.log(result);
response.status(200).send({
message:
'Your email has been succesfully added to the mailing list. Welcome 👋',
});
})
.catch((error) => {
response.status(500).send({
message:
'Oups, there was a problem with your subscription, please try again or contact us',
error: error as string,
});
}
);
if (result.status === 200) {
response.status(200).json({
message:
'Your email has been succesfully added to the mailing list. Welcome 👋',
});
} else {
response.status(500).json({
error:
'Oups, there was a problem with your subscription, please try again or contact us',
});
}
}
}

View File

@@ -15,7 +15,10 @@ interface Request extends NextApiRequest {
};
}
const sendGrid = (request: Request, response: NextApiResponse): void => {
const sendGrid = async (
request: Request,
response: NextApiResponse
): Promise<void> => {
if (request.method === 'POST') {
sgMail.setApiKey(process.env.SENDGRID_SECRET || '');
@@ -29,20 +32,25 @@ const sendGrid = (request: Request, response: NextApiResponse): void => {
reply_to: request.body.email,
};
sgMail
.send(message)
.then(() => {
response
.status(200)
.send({ message: 'Your email has been sent', success: true });
})
.catch((error: string) => {
console.error(error);
response.status(500).send({
message: 'There was an issue with your email... please retry',
error,
try {
const result = await sgMail.send(message);
console.log(result);
if (result) {
response.status(200).json({
message:
'Your message has been succesfully sent. Thank you for your feedback.',
success: true,
});
});
}
} catch (error: unknown) {
if (error) {
response.status(500).json({
error:
'Oups, there was a problem with your email, please try again or contact us',
success: false,
});
}
}
}
};
export default sendGrid;