Toggle visibility of success or danger notification depending on React response

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

Answer №1

This alert system I created is functioning perfectly

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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring ways to loop through objects in a React application

I'm trying to figure out how to modify the code below to iterate through a custom object I have created. function itemContent(number) { return ( <div > <div className="item"> <div className="itemPic& ...

Unpacking a mongoose record

During my project using mongoose, I encountered a issue. I am trying to retrieve all documents that contain a specific key and value pair role: USER. Although I am able to retrieve a list of documents, I am struggling to access the values of certain fields ...

The upload of files via Websockets is displaying corruption or improper encoding issues in PHP and JavaScript

I am currently working on developing websocket scripts using PHP and JS, but I am facing an issue when it comes to saving a file (image). When sending from JS: $('#frmChatFile').on("submit",function(event){ event.preventDefault(); var f ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

The Vue.js mixin is not functioning properly within the component as expected

I've created a mixin in Vue.js for a simple digital watch: var myMixin = { data () { clockInt: '', clock: '', currentTime: new Date() }, mounted () { this.intervalSetup(); }, ...

Creating tilted divs with dynamic height to perfectly fit the content

I'm struggling to incorporate this design into my webpage; I can't seem to get the right div's height to match the left div as depicted in the second image. Can someone offer some assistance? Additionally, when viewed on mobile, the squares ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

concealing frames within a frameset with the help of javascript

Is it possible to create multiple frames with individual borders, each featuring an icon that allows users to hide and show the frame by clicking on the icon? ...

Trouble with AJAX Post Request: Missing JSON Response

Below is the AJAX request I have created: var data = modalDom.find("form").serializeObject(); data["returnJson"] = true; $.ajax({ type: "POST", url: "/companies/edit/", data: data, dataType: "JSON", success: function (result) { ...

How can I tally the frequency of characters in a given string using Javascript and output them as numerical values?

I am in the process of tallying the frequency of each individual character within a given string and representing them as numbers. For example, let's consider the string "HelloWorld". HELLOWORLD There is one H - so 1 should be displayed with H remov ...

Guarantee the correct sequence of following HTTP ajax requests within AngularJS

Imagine a basic search form with autocomplete that triggers a $http.get() request on keyup/keypress: <input type="text" ng-model="keyword" ng-change="makeRequest()"> and $scope.makeRequest = function() { $http.get(url).then(function(res) { ...

Issue with escaping string quotes in Django and Jquery

When dealing with posts saved by users in a small forum, I encountered an issue with words surrounded by quotes. This error occurs when trying to handle these strings with JavaScript. To address this problem, I developed some jQuery code that utilizes the ...

Learn how to toggle a React component with the help of Redux Toolkit

I'm facing an issue with toggling a React component using Redux Toolkit. I am unable to access the value of "toggle" as the useSelector in Redux Toolkit is returning "undefined". The code seems to be not functioning properly. I would appreciate any s ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

The CSS selector is not properly adhering to the parent restriction as it attempts to find the div childCollapsible that has the attribute data-onthemovecollapsible set to true

Imagine a scenario that is much more complex, but let's try to simplify. I am attempting to choose the siblings of an element with the class 'sss' using $('.sss').parent().parent().find(">div.childCollapsible>div[data-onthem ...

Modifying properties of an array object using React hooks

Is there a way to toggle the boolean property for all objects using the React useState hook? const [showCard, setShowCard] = useState([ { id: 1, show: true }, { id: 2, show: true } ]); ...

Tips for adjusting elements to accommodate an expanding element

My webpage contains a complex hierarchy of divs. Here's an example: <div id="bill-list"> <div id="bill-panel"> <!-- Bill --> <div class="bill"> <!-- Bill description - Holds Bill details --> ...

A method for determining the length of text lines within a table cell (td) and revealing additional content upon clicking

I want to implement a feature where clicking on "see more" will reveal the full content within a table cell. The criteria for displaying "see more" is when the text inside the table cell spans more than 3 lines, then show the prompt and expand to show the ...

Indicate to the user whether the form submission was successful or not

I have designed a form that transmits data to a CRM. When I implemented a basic HTML form and submitted the data to the server, it would refresh my webpage and display either: {"success":false,"error":{"message":"<whatever the error is>"}} or {"su ...