Search code examples
reactjssettimeout

Using SetTimeout() in React


I'm trying to change a state after some time so I can change DOM and using setTimeout() for this but I could not make it work. Here is code:

  function Contact() {
  const [send, setSend] = useState(false);

  const submitHandler = async values => {
    const { fullname, email, subject, message } = values;

    if (fullname && email && subject && message) {
      const response = await fetch('/api/sendgrid', {
        method: 'post',
        body: JSON.stringify({
          fullname,
          email,
          subject,
          message,
        }),
      });
      console.log(response);
      if (response.status === 'ok') {
        setSend(true);
        setTimeout(() => {
          setSend(false);
        }, 3000);
      }
    }
    reset();
  };

  return <something/>

So send variable should change after 3s and I need to clearTimeout() afterwards. Where should I make changes?


Solution

  • it's silly me. my last if statement was wrong. it should be as follows.

    if (response.ok) {
        setSend(true);
        setTimeout(() => {
          setSend(false);
        }, 3000);
      }