0

I have anonChange for an input where call I update state with the value of the input by calling the function enteredTextHandler. In that same function, I then try to call a for-loop based on the length of the text, but it doesn't work the first time I run it, only the second+ times. For example, if I type "AB" into the input field, once I type the "B" the console.log('inputText: ', this.state.inputText) show up with "A" in them. If I then type "C" it will update to "AB" but not show the C. This then messes up the following for-loop. Any help is appreciated:

  enteredTextHandler = (event) => {
    this.setState({inputText: event.target.value})
    console.log('inputText: ', this.state.inputText)
    let charArray = []
    for(let i=0; i<this.state.inputText.length; i++){
      charArray.push({
      letter: this.state.inputText[i],
      key: i})
    }
    console.log('charArrar: ', charArray)
    this.setState({stateCharArray: charArray})
  }
Grip
  • 25
  • 3
  • 1
    setState is async, do `let value=event.target.value`; and use this value in place of `this.state.inputText` at all the places in this function, also instead of using setState twice use only once at the end of the function, like this: `this.setState({stateCharArray: charArray, inputText: value})`. If you want to use `this.state.inputText` then use setState callback method and use loop inside. *Better to use first one* – Mayank Shukla Feb 20 '18 at 04:00
  • @Mayank Shukla I just tested that and it works beautifully. Thanks you. – Grip Feb 20 '18 at 04:05

0 Answers0