1

I am working on displaying a "message" on the component based on the server response, and i wanted that message to disappear after 5 second. I tried my best with setTimeout but no luck, can you help me?

Here is my code:

import React, { useState } from "react";
import { Form, Button, Container, Row, Col} from 'react-bootstrap'
import axios from 'axios'

export default function Users() {

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("")
  

  function handleSubmit(e){
    e.preventDefault()
    const credential = { email, name };
      axios
        .post('/', credential)
        .then(response => {
          if(response.status === 201) {
            resetInputs()
            setMessage(response.data.message)
          }
        })
        .catch(error => {
          if (error.response.status === 409) {
            setMessage(error.response.data.message)
          }
        })
  }


  function resetInputs(){
    setEmail("")
    setName("")
  }
     
  return (
  <div className="form">
            <div className="hero-container">
              <h1>Welcome to <span className="hi">my</span><span>website</span></h1>
              <h5>Enter your name and your email to join our waiting list!</h5>
              <p></p>
                <div>
                 {message}
                </div>
              <p></p>
  </div>
  )
}
1
  • "I tried my best with setTimeout but no luck" What did that code look like? We can't tell you what was wrong with it if you don't show it to us. Commented Jul 9, 2020 at 8:24

3 Answers 3

2

You call setTimeout after setting the message, telling it to fire after five seconds, and then clear the message:

function handleSubmit(e){
  e.preventDefault()
  const credential = { email, name };
    axios
      .post('/', credential)
      .then(response => {
        if(response.status === 201) {
          resetInputs()
          setMessage(response.data.message)
        }
      })
      .catch(error => {
        if (error.response.status === 409) {
          setMessage(error.response.data.message)
        }
      })
      .finally(() => {       // ***
        setTimeout(() => {   // ***
            setMessage("");  // *** If you want to clear the error message as well
        }, 5000);            // *** as the normal message
      });                    // ***
}

or

function handleSubmit(e){
  e.preventDefault()
  const credential = { email, name };
    axios
      .post('/', credential)
      .then(response => {
        if(response.status === 201) {
          resetInputs()
          setMessage(response.data.message)
          setTimeout(() => {   // *** If you only want to automatically clear
              setMessage("");  // *** this message and not an error message
          }, 5000);            // ***
        }
      })
      .catch(error => {
        if (error.response.status === 409) {
          setMessage(error.response.data.message)
        }
      });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, this solved my problem. deeply appreciated!
0

You can add setTimout to your axios call, or you can reset it independently like this:

import { useEffect } from "react";

...

useEffect(() => {
  let isUnmounted = false;

  if (message !== "") {
    setTimeout(() => {
      if (!isUnmounted ) {
        setMessage("");
      }
    }, 5000);
  }

  return () => { isUnmounted = true; };
}, [message])

isUnmounted prevents using setMessage() in an unmounted component, it is possible for a user to close the component before time is reached.

Comments

0

Something like this may work (untested):

const useTimedState = (initialState, duration) => {
    const [state, setState] = setState(initialState);
    useEffect(() => {
        if (typeof state === 'undefined') {
            return;
        }
        const timer = setTimeout(() => {
            setState();
        }, duration);
        return () => clearTimeout(timer);
    }, [state]);
    return [state, setState];
}
export default function Users() {

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useTimedState(undefined, 5000);
  

  function handleSubmit(e){
    e.preventDefault()
    const credential = { email, name };
      axios
        .post('/', credential)
        .then(response => {
          if(response.status === 201) {
            resetInputs()
            setMessage(response.data.message)
          }
        })
        .catch(error => {
          if (error.response.status === 409) {
            setMessage(error.response.data.message)
          }
        })
  }
}

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.