1

I'm really sorry I'm posting this as it sounds crazy. I got a method to validate some inputs I have in a form inside a modal.

So I check on every this.state.variable and doing a push to an aux array to be then set to the original fieldErrors array.

But for some reason, when I check aux before setting, length is 5. After setting to fieldErrors, i notice length is 0. What's going on?

Here's the code:

_validateMissingFields: function() {
    var aux = [];

    if (this.state.variable1.length === 0) {
        aux.push('variable1');
    }

    if (this.state.variable2.length === 0) {
        aux.push('variable2');
    }

    if (this.state.variable3.length === 0) {
        aux.push('variable3');
    }

    if (this.state.variable4.length === 0) {
        aux.push('variable4');
    }

    if (this.state.variable5.length === 0) {
        aux.push('variable5');
    }

    console.log(aux.length) // -> shows 5
    this.setState({ fieldErrors: aux });
}

Later on, when I do this.state.fieldErrors.length after this method, shows 0.

By the way, this is how I'm initializing fieldErrors:

getInitialState: function() {
    return {
        variable1: '',
        variable2: '',
        variable3: '',
        variable4: '',
        variable5: '',
        fieldErrors: []
    }
},
msqar
  • 2,940
  • 5
  • 44
  • 90
  • 2
    Possible duplicate of [setState in reactjs is Async or Sync](http://stackoverflow.com/questions/36085726/setstate-in-reactjs-is-async-or-sync) – jontro May 12 '17 at 00:12
  • 1
    See this question too for more info http://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately – jontro May 12 '17 at 00:13
  • Omg @jontro, didn't know it was async :S that is kinda ugly, i thought it would be an instant set as in any other framework. Thanks! Put it as an answer and i will tick it. – msqar May 12 '17 at 00:16
  • this framework is so full of async stuff that is getting annoying :'( a lot of promises and stuff happening simultaneously haha.. is driving me nuts! – msqar May 12 '17 at 00:19
  • 1
    ;) yeah takes a while to get used to. It's not often I have to read the state after setting it though in the same pass – jontro May 12 '17 at 00:24

2 Answers2

2

React setState is asynchronous which is why this.state cannot be read immediately.

See the docs for more info https://facebook.github.io/react/docs/react-component.html#setstate

jontro
  • 10,241
  • 6
  • 46
  • 71
1

setState is asynchronous, as has been mentioned a couple times, but it also accepts a callback function as a second parameter so if what you're trying to do with length can be done in a callback you can do something like

this.setState({ fieldErrors: aux }, () => {
  console.log(this.state.fieldErrors.length); // Or whatever you're trying to do
};
Ben Hare
  • 4,365
  • 5
  • 27
  • 44
  • thanks, you're right too but im giving the tick to jontro since he helped me first :) thanks tho! – msqar May 12 '17 at 01:15