Michaela
Michaela

Reputation: 267

React - setState on input field not working

I seem to be missing something, why is the setState not working for me?! If i pull the initial state into value of the text input field to make it controlled, the setState does not work for me...what am I doing wrong?

      class Module extends Component {
          constructor() {
              super()

              this.state = {
                  text: 'text'
              }

              this.handleInputChange = this.handleInputChange.bind(this)
          }

          handleInputChange(event) {
              console.log('handle input change')
              this.setState = ({
                  text: 'new state: ' + event.target.value
              })
              console.log(event.target.value)
          }

          render() {
              return (
                  <div>
                      <input
                          type="text"
                          value={ this.state.text }
                          onChange={ this.handleInputChange }
                      />
                  </div>
              )
          }
      }

      export default Module

Upvotes: 6

Views: 26451

Answers (3)

Gus
Gus

Reputation: 36

Store the changed value, setState() is asynchronous.

handleInputChange(event) {
  const myValue = event.target.value;
  this.setState({
    text: myValue
  })
}

Upvotes: 1

NIRudman
NIRudman

Reputation: 1

Why do you have 'new state: ' in the setState? The onChange function is called on every key press or change, so you shouldn't add your own text inside of the setState function. If you wanna use ES6, you can change the onChange call to:

(event) => this.handleInputChange(event.target.value)

and the handleInput function to:

handleInputChange(value) {
  this.setState({
    text: value
  })
}

If you need the 'new state: ' string before the input text then put it inside of a span before the input instead.

Upvotes: -1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

Because setState is asynchronous. But fortunately there is a callback parameter in the method call which you can use to get the value like this

    this.setState({
        text: 'new state: ' + event.target.value
    }, () => {
        console.log(text)
    })

Btw you are not assigning anything to setState it's a method call. Besides that since events are synthetic events in React you have to store the current target in a variable to not lose the event for example like this

    const saveValue = event.target.value;
    this.setState({
        text: 'new state: ' + saveValue 
    });
    console.log(saveValue);

Upvotes: 8

Related Questions