-2

I have a very simple setup. I just have one controlled input and I want to console.log the input.

import React, {useState} from 'react'
   
const App = () => {
   const [text, setText] = useState('')
   
   const handleChange = event => {
      event.preventDefault()
      setText(_prev => event.target.value) 
      consoel.log(text) 
   }
   
   return(
      <div>
        <input type="text" value={text} onChange={handleChange} />
      </div>
   )
}

I seem to only be getting the one before the actual state. For example if I type 'abc' in the console i only see 'ab' and after typing a fourth character I see 'abc'. Why is my state always one input behind?

(trying to change the state in the following manner setText(event.target.value) has provided the same results).

skyboyer
  • 22,209
  • 7
  • 57
  • 64
eitan
  • 59
  • 8
  • Read https://reactjs.org/docs/hooks-state.html to understand how to use the setter method from useState. It doesn't take a callback. You also misspelled "console" – Andy Ray Jun 21 '21 at 19:06
  • 1
    Does this answer your question? [console log the state after using useState doesn't return the current value](https://stackoverflow.com/questions/54867616/console-log-the-state-after-using-usestate-doesnt-return-the-current-value) – MrSrv7 Jun 21 '21 at 19:18

1 Answers1

1

Due to it's asynchronous behavior you can't directly get value right after it's being updated. To get the value, you can use the effect hook which will check for the change and acts upon the behavior:

useEffect(() => {
  console.log(text) // act upon
}, [text]) // when text changes, it runs

Also, side note, you just have to do:

setText(event.target.value)
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231