2

When i used onchange event to update my state i have a delay character

this is my class

var DivInput = React.createClass({
    getInitialState: function() {
        return {
            content: ''
        }
    },
    onChange: function(e) {
        var value = e.target.value
        var name = e.target.name
        this.setState({
            content: value
        });
        console.log(this.state.content)
        this.props.onUpdateState(name, value)
    },
    render: function() {
        return (
            <div className="form-group">
            <label className="col-md-4 control-label" for="textinput">{this.props.content}</label>  
                <div className="col-md-4">
                <input onChange={this.onChange} name={this.props.name} type={this.props.type} value={this.state.content} className="form-control input-md" />
            </div>
        </div>
        )
    }
})

i have yet initiated my state at '' with getInitialState, and update it when my input change but i have this problem :

if i write : "a"

this.state.content = ""

if i write : "ab"

this.state.content = "a"

for input at = "abc"

this.state.content = "ab"

etc...

Someone has already fixed this problem ?

thanks

Fantasim
  • 876
  • 1
  • 12
  • 32
  • https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately – ByteMe Sep 04 '17 at 06:11

1 Answers1

2

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

See more about it https://facebook.github.io/react/docs/component-api.html

Dmitriy
  • 3,745
  • 16
  • 24
  • thanks but doc doesn't say how i can fix this problem. How can I force state to update – Fantasim Mar 17 '16 at 21:09
  • 1
    You can do so, but it is not the right way: `this.state.content = value; this.forceUpdate();` instead of `this.setState({content:value});` but this is not a good way! – Dmitriy Mar 17 '16 at 21:11
  • Okay thank u, so what is the best way ? (Although I have to change all) – Fantasim Mar 17 '16 at 21:13
  • I guess, the best way try not using `this.state.property` after you call `setState` and try to find another way to write code. :) – Dmitriy Mar 17 '16 at 21:16