Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How We can get the state value immeditely after changing the state?

```import { useState } from 'react';

export default function FeedbackForm() {
  const [name, setName] = useState('');

 async function handleClick() {
    setName(prompt('What is your name?'));
    await alert(`Hello, ${name}!`);
  }

  return (
    <button onClick={handleClick}>
      Greet
    </button>
  );
}```

I’am trying to get the state name value immedietly?
So tell me that how we can get the value instantly or there is any method to do this that i can get the value in the alert ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You cannot get the value immediately, as the function was created when the value of name was ''. Once the event handler has finished executing, React will re-render the component, which will now have the updated value for name.

You can store the returned value from the prompt in a local variable, and then use that instead:

function handleClick() {
  const enteredName = prompt('What is your name?');
  setName(enteredName)
  alert(`Hello, ${enteredName}!`);
}

Also note that I have not set the handleClick function as async. alert does not return a Promise, so using await in front of it has no effect.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading