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.
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>
)
}