There is such a React component:

import React from 'react'; import './AppSearch.css' class AppSearch extends React.Component { constructor() { super(); this.state = { request: '', } this.onSearch = (e) => { this.setState({ request: e.target.value, }) console.log(this.state.request); } } render () { return( <input className='AppSearch' value={this.state.request} onChange={ this.onSearch } placeholder = 'Search parametr' /> ) } }; export default AppSearch; 

For some reason, the onChange event does not work correctly. I can not figure out why.

The onSearch function first changes the request , and then only outputs this value, but it turns out as if it works the other way around:

enter image description here

The screenshot shows that I entered three deuces, and there are only two in the console. With what it can be connected?

    2 answers 2

    setState does not change the state immediately (during the execution of the piece in which it is declared). For a piece of code after setState state will be the same as before. Here is what you need to do in your case:

     this.onSearch = (e) => { let val = e.target.value; this.setState({ request: val }) console.log(val); } 

    I think the logic is clear.

      setState has a callback :

       this.setState({ request: e.target.value }, () => { console.log(this.state.request) }) 

      This is how it will work correctly (the behavior you expect) :)