提交成功或失败后,如何以反应形式显示烤面包机警报?

问题描述

我想知道如何在单击显示“您的信息已发送”的“发送信息”按钮时显示烤面包机警报,并且如果失败则显示“无法发送您的信息,这是问题!” >

我要发送的代码是:

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

解决方法

一旦解析或拒绝,response对象将具有一个名为status的属性,该属性指示请求是由服务器(API)解析还是拒绝。您可以使用status属性来相应显示警报。

示例

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