U
U
uzi_no_uzi2018-11-18 13:45:56
React
uzi_no_uzi, 2018-11-18 13:45:56

Why is the event not firing correctly?

I have this 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 is not working correctly. I can't figure out why.
The onSearch function first changes the request, and then only displays this value, but it turns out as if it works the other way around:
5bf142db74055656563235.jpeg
The screenshot shows that I entered three twos, but there are only two in the console. With what it can be connected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-11-18
@uzi_no_uzi

First, events do not work - none and never. Event handlers fire. Secondly - between "wrong" and "not the way I would like" there is a significant difference, try to realize it.
The setState method is asynchronous. If you want to access the changed state, use the callback:

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question