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

Why React returns empty when calling a function for the first time?

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.

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

How to solve this and why happens?

>Solution :

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]);
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