0

I'm learning React. There is a component. When I write text to the input (for example, the text: "stackoverflow"), onChange fires, "stackoverflow" is written to the state (That's right), but for some reason console.log displays "stackoverflo" for me (without last letter).

Why is this happening?

import { Component } from "react";
import "./style.css";

class SearchPanel extends Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };
  }

  handleInputChange = (event) => {    
    // let term = event.target.value;
    this.setState({ value: event.target.value });    

    console.log(this.state.value);
    // this.props.searchUpdate(this.state.value);
  };

  render() {
    return (
      <input
        type="text"
        className="form-control search-input"
        placeholder="Test"
        value={this.state.value}
        onChange={this.handleInputChange}
      />
    );
  }
}

export default SearchPanel;
Digweed
  • 2,819
  • 2
  • 10
  • 7
  • 1
    `setSate` is asynchronous, You need to use the async callback (https://stackoverflow.com/questions/33088482/onchange-in-react-doesnt-capture-the-last-character-of-text) – Clément Gibert Apr 19 '22 at 09:53

1 Answers1

1

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why the setState function in class components accepts an optional second parameter which is a callback function that will automatically run after the state has finished updating.

Example:

handleInputChange = (event) => {    
  this.setState({ 
     value: event.target.value
  }, () => { 
     console.log(this.state.value);
  });
};

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: this is only relevant for class components, it's a different story in functional components.

Check the documentation for more info.

tomleb
  • 2,409
  • 2
  • 9
  • 24