Boidurja Talukdar
Boidurja Talukdar

Reputation: 696

How to display data entered in input field in react js?

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.

Upvotes: 0

Views: 1681

Answers (2)

Tarukami
Tarukami

Reputation: 1160

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])

Upvotes: 1

Matthieu Bouxin
Matthieu Bouxin

Reputation: 127

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);
}

Upvotes: 0

Related Questions