Can someone help me display a React Bootstrap Alert based on the response message from a fetch request? I've been trying different approaches, but I seem to have hit a roadblock with my understanding of React, especially hooks.
Here is the code snippet:
import React, { useState } from 'react';
import { Alert } from 'react-bootstrap';
Below is my function:
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);
});
}
Here are the Alert components in the code, they are initially hidden due to 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>
);