0

When I enter the first character in the input element I get "empty string".

function form(props) {
    // function getData(e){
    //     e.preventDefault()
    //     console.log(e.target[1].value)
    const [title, setTitle] = useState("")

    function getTitle(e){
        setTitle(e.target.value)
        console.log(title) //First time shows "empty string"
    }

    
    return (
        <form >
            <div>
                <label >Title</label>
                <input type="text"  name="title" onChange={getTitle} />
            </div>
    </form>)

The way I see it, I enter a character in the input element, "onChange" event is fired, the function getTitle is run, its sets the "title" variable, which is hooked to the useState hook, and next I console the result. Following this reasoning I expect to get the first character entered. Instead I get "empty string". From the second character onwards the console prints the characters.

With "onInput" function happens the same.

How to solve this and why happens?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Carlitos_30
  • 371
  • 4
  • 13

2 Answers2

2

Setting state is asynchronous, so your console.log is running before the state is set. If you use a useEffect hook to view the state, you should see the value. The useEffect hook runs post-render, so you will see your updated state information at that time.

useEffect(() => {
   console.log(title);
}, [title]);
sma
  • 9,449
  • 8
  • 51
  • 80
1

setTitle asyncronous, you must check title changes in useEffect

useEffect(() => {
   console.log(title);
}, [title])
Vitaliy Rayets
  • 2,299
  • 1
  • 6
  • 12