2021年3月26日星期五

Show/hide success or danger alert based on response in React

Kindly assist showing React Bootstrap Alert based on response message from fetch. I tried numerous logic but my knowledge of React seems to reach its limits, particularly hooks

Below is my code

import React, { useState } from 'react';  import { Alert } from 'react-bootstrap';    

My function states as below here,

export default (props) => {    const [invisibleSuccess, setInvisibleSuccess] = useState(false);    const [invisibleDanger, setInvisibleDanger] = useState(false);    const [message, setMessage] = useState('');    

Submit handler

 async function submitHandler() {     fetch("http://example.api.com", requestOptions)        .then(response => response.json())        .then(result => {          switch (result.message) {              case 'success':              setInvisibleSuccess(true);              break;              case 'error':              setInvisibleDanger(true);              break;              default:              setMessage(result.message);          }        })        .catch(error => {          setMessage(error.message);        });   }  

and my Alerts as below, they are hidden by default because of their false states

return (  <div className="row d-flex justify-content-center">          <div className="col-sm-12">            <div className="card">              <div className="card-details">                <div className="row d-flex justify-content-center">                  <div className="col-sm-12 text-center">                     <Alert show={invisibleSuccess} variant="success"><Alert.Heading>Payment made Successfully!</Alert.Heading></Alert>                       <Alert show={invisibleDanger} variant="danger">                        <Alert.Heading>Payment Failed!</Alert.Heading>                            <hr />                            <p className="mb-0">                                 {message}                            </p>                        </Alert>                 </div>              </div>            </div>         </div>      </div>  </div>  );    
https://stackoverflow.com/questions/66827916/show-hide-success-or-danger-alert-based-on-response-in-react March 27, 2021 at 12:07PM

没有评论:

发表评论