Search code examples
reactjsinputreact-hooksonchange

Input value onChange - React Hooks


I'm trying to collect the value typed in a input box, but when I use onChange I can only get the previous value. For example after I just typed "text" the latest value to be collected would be "tex"

import React, {useState} from 'react';
import './SearchBar.css';

const SearchBar = (props) => {

    const [input, setInput] = useState('');

    const onChange = (e) => {
        setInput(e.currentTarget.value);
        console.log(input);
    }

    let sugestionList = (
        <ul>
            <li>item 1</li>
            <li>item 2</li>
        </ul>
    )



    return(
        <div className="search-bar">
            <input type="text" placeholder={props.placeholder} onChange={onChange}/>
            {sugestionList}
        </div>

    )
}

Solution

  • That's because updating a state is an asynchronous task. To get the latest state you can use useEffect() hook.

    useEffect(() => {console.log("input state is", input)}, [input]) //add the state in dependency array and this useEffect will run whenever state changes//