```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 ?
3
Answers
You use useEffect to do something whenever state changes.
One simple way that I would suggest you here is to use constant
for example ->
This way you will be able to use updated state value.
I hope it solves the use case for your code
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 forname
.You can store the returned value from the prompt in a local variable, and then use that instead:
Also note that I have not set the
handleClick
function asasync
.alert
does not return aPromise
, so usingawait
in front of it has no effect.