Reputation: 117
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>
);
Upvotes: 1
Views: 3010
Reputation: 426
I have build alert like this and works well
import { useState } from 'react';
import { Alert, Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
const [showDangerAlert, setshowDangerAlert] = useState(false);
const [showSuccessAlert, setshowSuccessAlert] = useState(false);
const getData = async () => {
let resp = await fetch('https://jsonplaceholder.typicode.com/todos/2');
let data = await resp.json();
// data.completed = true;
console.log(data);
switch (data.completed) {
case false:
return setshowDangerAlert(true);
case true:
return setshowSuccessAlert(true);
default:
return alert('no data found regarding this');
}
};
return (
<div className="App">
<Button onClick={() => getData()}>fetch todo status</Button>
<Alert
show={showDangerAlert}
variant="danger"
className="w-25 mt-3 ml-3 "
>
This is a error Message
</Alert>
<Alert
show={showSuccessAlert}
variant="success"
className="w-25 mt-3 ml-3 "
>
This is a success Message
</Alert>
</div>
);
}
export default App;
Upvotes: 3