How to display a toastr alert in a react form after submit succeed or failed?

I would like to know how to display a toastr alert when clicking the “send information” button showing “Your information has been sent” and if it fails “Your information could not been sent, here is a problem!”

the code i have for sending is:

 const sendMail = async (data: FormData) => {
    const response = await fetch('https://us-central1-my-website.cloudfunctions.net/apply-function', {
      method: 'POST',
      body: data,
    });
  };

Answer

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} />
        </>
    );
};