Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss react error messages after a timeout

I am trying to display some react error messages and hide them after a timeout of 5 seconds. Below is the code:

import * as React from 'react'
import {ErrorInfo} from '../Twilio/api'
export const Error = ({type, message, visible}: ErrorInfo) => (
    // visible=true,
    setTimeout(function () {
        visible = false
    }, 5000),
        visible ?
            <div>
                <p>
                    <strong>{type}:</strong> {message}
                    <br/>
                    <small>
                        UI version: <code>{GLOBAL_VERSION}</code>
                    </small>
                </p>
            </div> : <span/>
)

ErrorInfo is as follows:

export type ErrorInfo = {
    type: string
    message: string
    visible: boolean
}

However, visible is being set to undefined and therefore error message is not getting displayed. If I set it to true while exporting Error, then it is getting displayed by the Header element is not getting removed when visible becomes false.

like image 507
Vipin Verma Avatar asked Feb 11 '26 01:02

Vipin Verma


1 Answers

you'd want to control the visible state in your Error component.

And then, you can use useEffect to hide the error after 5 secs (with proper cleanup)

export const Error = ({ type, message }: ErrorInfo) => {
   const [visible, setVisible] = useState(false)
   useEffect(() => {
     // message is empty (meaning no errors). Adjust as needed
     if(!message){
      setIsVisible(false)
      return
     }
     // error exists. Display the message and hide after 5 secs
     setIsVisible(true)
     const timer = setTimeout(() => {
       setIsVisible(false)
     }, 5000);
     return () => clearTimeout(timer);
   }, [message]) // executes every time `message` changes. Adjust as needed
   if(!visible) return null
   return (
      <div>
        <p>
            <strong>{type}:</strong> {message}
            <br />
            <small>
                UI version: <code>{GLOBAL_VERSION}</code>
            </small>
        </p>
    </div>
   )
}
like image 187
kkesley Avatar answered Feb 13 '26 14:02

kkesley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!