skip to Main Content

I want to implement toastify inside my toBeCalledByEventListener() function .

actually I don’t know where I implement those in my function:

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

and

const notify = () => toast("Wow so easy!");

and

<button onClick={notify}>Notify!</button>

any suggestion please.

my function look like this:I want to implement toastify here

async function toBeCalledByEventListener() {
    try {
        const response = await fetch('/generate_pdf', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        const responseData = await response.json();
        const pdfURL = responseData.pdf_url;
        localStorage.setItem("pdf_url", pdfURL)
        // window.open(pdfURL, '_blank');
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
    }
    catch (error) {
        console.error('Error fetching data:', error);
    } 
};

4

Answers


  1. You just need to call the toast function wherever you need it.

    import { ToastContainer, toast } from 'react-toastify';
    import 'react-toastify/dist/ReactToastify.css';
    
    const notify = () => toast("Wow so easy!");
    
    async function toBeCalledByEventListener() {
       ...
         // if the response was successful call the notification function
         const responseData = await response.json();
         const pdfURL = responseData.pdf_url;
         localStorage.setItem("pdf_url", pdfURL)
         // window.open(pdfURL, '_blank');
         notify()
         if (!response.ok) {
           toast("An unexpected error occurred, please try again later.")
           throw new Error('Network response was not ok');
         }
    
    
       ...
    }
    
    
    Login or Signup to reply.
  2. I guess you want to toast where you console. try the code below:

    async function toBeCalledByEventListener() {
        try {
            const response = await fetch('/generate_pdf', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            const responseData = await response.json();
            const pdfURL = responseData.pdf_url;
            localStorage.setItem("pdf_url", pdfURL)
            // window.open(pdfURL, '_blank');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
        }
        catch (error) {
            toast(error) // where i add some code
            console.error('Error fetching data:', error);
        } 
    }
    

    Because the function named notify cannot pass any params, just use the function toast instead.

    Login or Signup to reply.
  3. it is the function changes

    async function toBeCalledByEventListener() {
          try {
            const response = await fetch('/generate_pdf', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
            });
        
            const responseData = await response.json();
            const pdfURL = responseData.pdf_url;
            localStorage.setItem("pdf_url", pdfURL);
        
            // Display a success toast
            toast.success("PDF generated successfully!");
        
            // window.open(pdfURL, '_blank');
        
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
          } catch (error) {
            // Display an error toast
            toast.error('Error generating PDF:', error.message);
          }
        }
    

    your app.js changes :

    function App() {
      // ... other components
    
      return (
        <div>
          {/* ... other content */}
          <ToastContainer /> {/* Add this line */}
        </div>
      );
    }
    
    Login or Signup to reply.
  4. Here I have modified your code and make it easy to use.

    Make sure you have react-toastify installed. You can install it using npm
    https://www.npmjs.com/package/react-toastify

    Import the necessary components and styles from react-toastify at the top of your file.

    // Import required dependency 
    import React, { useEffect } from 'react'
    import { ToastContainer, toast } from 'react-toastify';
    import 'react-toastify/dist/ReactToastify.css';
    
    const ErrorHandling = () => {
        
        // Create a function that will be responsible for showing the error notification. In your case, it's the notify function.
        const notify = (msg) => toast.error(msg);
    
        async function toBeCalledByEventListener() {
            try {
              const response = await fetch('/generate_pdf', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
              });
          
              const responseData = await response.json();
              const pdfURL = responseData.pdf_url;
              localStorage.setItem('pdf_url', pdfURL);
          
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
          
            } catch (error) {
              console.error('Error fetching data:', error);
    
            //   Update your error handling logic to use the notify function whenever an error occurs.
            notify('Network response was not ok');
            }
          }
          
    
          useEffect(()=>{
            toBeCalledByEventListener();
          },[])
    
      return (
        // Finally, render the ToastContainer component at the root level of your component.
        <>
         <ToastContainer  />
        </>
      )
    }
    
    export default ErrorHandling
    

    This will resolve your problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search