Search code examples
reactjsreact-toastify

how do i make to appear the react toastify without using onClick button? it should appear once the page loads


the code I'm showing is a react toastify library with onClick button and custom autoclose set time for 1 minute. I want to use the library without using the button but when the page loads can somebody help me how to achieve that?

import React, { useRef, useEffect } from "react";
import * as tf from "@tensorflow/tfjs";
import Webcam from "react-webcam";
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
toast.configure();

function AppMain() { 

  const notify = () => toast("Fetching the Model Do not Close", {
    position: toast.POSITION.TOP_CENTER,
    autoClose: 60000});
 

  const webcamRef = useRef(null);
 

  };

  return (
    <div id="main" className="mainBlock">
      <div className="toasterbutton">
      
       
     <button onClick={notify}>Load Model</button>

     <ToastContainer />
    </div>
        <div id="caption"></div>
            <header style="margin-top:-2.5 rem;" className="container-fluid">
                <Webcam 
                ref={webcamRef}

                audio={false}
                muted={true} 
                style={{
                  position: "absolute",
                  marginLeft: "auto",
                  marginRight: "auto",
                  left: 0,
                  right: 0,
                  textAlign: "center",
                  zindex: 9,
                  width: 640,
                  height: 480,
            
                 }}
          
                 />

               
            </header>  
    </div>
  );
}

export default AppMain;

Solution

  • Try putting the function call and the function itself in a useEffect that will only run on mount.

    function AppMain() { 
      const [show, hide] = useState(true);
      
      useEffect(() => {
        const notify = () => toast("Fetching the Model Do not Close", {
          position: toast.POSITION.TOP_CENTER,
          autoClose: 60000
        });
    
        notify();
      }, [])
    

    This answer is a good explanation of the useEffect dependency array.