0

I want to show alert that message was sent (202) or has errors (else) on screen but this message should be clean after 3 seconds.

I usually use it only in useEffect hook, but I want it put in a condition

if (res.status === 200) {         
    setTimeout(function() {
        setStatus('success')   
    }, 1000);

Update:

I tried suggested snippets of code, but not working. Solution with [res...] cause a error, because react do not see variable like that. I go forward with this code, adding in if statement new variable which is associated with res... but still not work

      useEffect(() => {

        const timer =  ""
    

        if (kupa === "sukces") {         
          const timer =  setTimeout(function() {
          setStatus('success')   }, 1000); 
         
      }
      if (kupa === "error") {         
        const timer =    setTimeout(function() {
              setStatus('error')   }, 1000); 
             }
              return () => clearTimeout(timer);

      },  [kupa]);
  • 1
    Does this answer your question? [Dismiss react error messages after a timeout](https://stackoverflow.com/questions/61625297/dismiss-react-error-messages-after-a-timeout) – Kadet Jun 21 '22 at 11:58
  • you can't dismiss browser alert('something') window as it passes control to the user and your code can only wait for he/she to close it. – DINK74 Jun 21 '22 at 12:12
  • change kupa from useEffect dependency to be [status]. also "sukces" in the condition to be "success" – Amr yasser Jun 21 '22 at 13:25

2 Answers2

0

I think you can add the condition inside useEffect and based on the res.status the component will be re-render. if the res.status === 200 then setStatus('success') will be updated.

useEffect(() => {
if (res.status === 200) {         
    setTimeout(function() {
        setStatus('success')   
    }, 1000);
 }
}, [res.status])
Amr yasser
  • 408
  • 5
  • 10
0

Try this one:

useEffect(() => {
        
    

        if (kupa === "sukces") {         
          
          setStatus('success')   
      }
      if (kupa === "error") {         
       
              setStatus('error')   
             }

         
              
                return () => {  setTimeout(function() {
                  setStatus('')  
                setKupa('') }, 3000); 
   }
               
                

      },  [kupa] );