Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to show error for few seconds react with 3 conditions?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Please help me in this to figure out this ?

>Solution :

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 !!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading