React bootstrap alert not showing

Viewed 1623

React react-bootstrap alert not showing

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

const ShowSuccess= () => {
  return (
    <Alert color='primary' fade={false}>check it out!</Alert>
  );    
}

export { ShowSuccess };

and here is the part where my alert box is called

import { ShowSuccess } from '../../Notifications';

export const fetchInfo= async () => {
    try {
      await getData();
      ShowSuccess();
    } catch (error) {
      console.log(error);
    }
  }
2 Answers

Yes, you can set a flag state to true whenever you made an API call. If the flag state is true then you can perform the necessary operation or task like showing an Alert box in your case else do the other task.

You can do the conditional rendering for displaying the alert box in JSX.

import React, {useState,useEffect} from "react";

function FetchInfo(){
  const [value, setValue] = useState(null);
  const [flag, setFlag] = useState(false);

  useEffect(() => {   
    async function fetch() {
      try {
        const data = await getData();
        setValue(data);     
        setFlag(true);
      } catch(e) {
        console.log(e);
      }
     fetch();
  },[])
   
  return (
   <> 
    {flag && 
     <Alert color='primary' fade={false}>check it out!</Alert>
    }   
  </>);
}
export default FetchInfo;

You need to set the state for the Alert to work. It is a React component. Include the component wherever you need to use the Alert and set it states after the API call is resolved.

function MyComponentWhereApiCallHappens() {
  const [show, setShow] = React.useState(false);

  async function apiCall() {
    const data = await fetchInfo();
    setShow(true); 
  }

  return (
     <div> 
       <Alert>
         /** alert content **/
       <Alert>
     </div>
  )
}

If you want to call something like an Alert from outside of the React component.

Use this library -> https://github.com/fkhadra/react-toastify

Related