skip to Main Content
```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


  1. You use useEffect to do something whenever state changes.

    
    export default function FeedbackForm() {
      const [name, setName] = useState('');
    
      useEffect(() => {
        alert(name);
      },[name]) // <- this is the dependency, useEffect is called whenever name changes.
    
     async function handleClick() {
        setName(prompt('What is your name?'));
    //    await alert(`Hello, ${name}!`);
      }
    
      return (
        <button onClick={handleClick}>
          Greet
        </button>
      );
    }```
    
    Login or Signup to reply.
  2. One simple way that I would suggest you here is to use constant

    for example ->

    import { useState } from 'react';
    
    export default function FeedbackForm() {
      const [name, setName] = useState('');
    
     async function handleClick() {
        const newName = prompt('What is your name?');
        setName(newName);
        await alert(`Hello, ${newName}!`);
      }
    
      return (
        <button onClick={handleClick}>
          Greet
        </button>
      );
    }
    

    This way you will be able to use updated state value.
    I hope it solves the use case for your code

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search