0

I want to show the username in the alert box. But so far it's not working. Here is my code:

function App() {

  const [nameInForm, setNameInForm] = useState("");

  const [username, setUserName] = useState("");

  const inputName = (event) => {
       setNameInForm(event.target.value);
  }

  const handleSubmit = () => {
       setUserName(nameInForm);
       alert("Welcome " + username);
  }

  return (
     <>
      <form onSubmit={handleSubmit}>
        <input type="text" value={nameInForm} onChange={inputName} />
        <button type="submit"> Login </button>
      </form>
     </>
  );
 }

If I don't use the form tag and use onClick={handleSubmit} on the button still the code does not work.

3

2 Answers 2

1

Setting state is kinda async operation. You can not use the new state value on the next line of code in console.log() or alerts etc... In your example, you already have the username in "nameInForm" state, you can use it

const handleSubmit = () => {
  setUserName(nameInForm);
  alert("Welcome " + nameInForm);
}

either "username" and useEffect hook can be used which is nice way to watch state changes:

//the function is updating state:
const handleSubmit = () => {
  setUserName(nameInForm);
}
// the useEffect hook shows new state after it has been updated
useEffect(() => {
  alert("Welcome " + username);
}, [username])
Sign up to request clarification or add additional context in comments.

3 Comments

But this alerts on each action right? He wants that on submit.
alert is called only when 'username' is changed on submit, not when input values while editing text input.
Yep. I was confused with the second state. This is the right way, I agree
0

You should not call setUserName in handleSubmit. As setUserName is asynchronous it will be resolved on next render so you should do

const handleSubmit = () => {
       alert("Welcome " + nameInForm);
}

Comments

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.