0

Hello i am new to react and i have a problem.. I want to set a Error Message and check if its empty.

This is my code:

const [errormsg, setErrorMsg] = useState("");


const register = (e) =>{

    if(firstname === "" || lastname === ""){
            setErrorMsg("Please fill out all Gaps!");
            e.preventDefault();
    }

    if(errormsg === ""){
    //DO SOMETHING
    }
}

But everytime it skips the part where it should stop. Because even if lastname is empty it continues but i dont know why because it should stop there.

I also added the line e.preventDefault(); because i want to show the error message to the user and if it reloads after every submit this does not work

Rezureax
  • 53
  • 5

1 Answers1

1

React state is a kind of asynchronous, you cannot expect next line have state set, so what you should do is

const [errormsg, setErrorMsg] = useState("");


const register = (e) =>{

    if(firstname === "" || lastname === ""){
            setErrorMsg("Please fill out all Gaps!");
            e.preventDefault();
    }
}

useEffect(() => {
  if(errormsg === ""){
    //DO SOMETHING
   }
}, [errormsg])

the callback in useEffect will execute every time errormsg change.

Hafeez Hamza
  • 794
  • 3
  • 16