Home > Software engineering >  I want to show error for few seconds react with 3 conditions?
I want to show error for few seconds react with 3 conditions?

Time:12-19

I am currently learning React and I have a situation where I want to show error message for few seconds also below three conditions must be satisfied.

First Case : If the message is empty (meaning no errors). Adjust it as accordance.

Second Case : If error exists then it will display the message and hide after 5 secs.

Third Case : It executes every time message changes. Adjust as per needed.

Please help me in this to figure out this ?

CodePudding user response:

Answer of your questions is :

const [visible, setVisible] = useState(false)

useEffect(() => {
  // CASE 1 :message is empty (meaning no errors). Adjust as needed
  if(!message){
    setIsVisible(false)
    return
  }

  //CASE 2: error exists. Display the message and hide after 5 secs

  setIsVisible(true)
  const timer = setTimeout(() => {
     setIsVisible(false)
  }, 5000);
  return () => clearTimeout(timer);
}, [message]) // CASE 3 : executes every time `message` changes. Adjust as needed

Hope this will match with your requirements.

Happy Coding !!

  • Related