Once resolved or rejected, the response
object will have a property called status
which indicates whether the request was resolved or rejected by the server (API). You can use the status
property to show alerts accordingly.
Example
import React from 'react';
const Mail = () => {
const [alert, setAlert] = React.useState({ show: false, message: '' });
const sendMail = async (data: FormData) => {
// It's better to use try catch block when writing an async function.
try {
const response = await fetch(
'https://us-central1-my-website.cloudfunctions.net/apply-function',
{
method: 'POST',
body: data,
}
);
if (response.status === 200) {
setAlert({
show: true,
message: 'Your information has been sent!',
});
}
} catch {
// If response was not successful.
setAlert({
show: true,
message: 'Your information could not be sent!',
});
}
};
return (
<>
{/* Other components.. */}
<Toaster show={alert.show} message={alert.message} />
</>
);
};