1

Not sure if this is a bug or a niggle, or simply how it's "supposed" to work, but...

Let's say I have a state like this :

state = {
  stuff: '',
}

And I update the state from a text input like this :

onChange = e => {
  this.setState({
    stuff: e.target.value
  });

  console.log(this.state.stuff.length);
}

The console log doesn't output the correct length when the text input is changed.

For example, if the text input contained the word 'things', the console log correctly reports that the length of stuff is 4 (As 0 is also counted as a number).

Now, if the client deletes one character, making stuff now contain 'thing' the console will report that the length of stuff is now 5 and not 3 as expected.

It's like it's counting the delete keypress as a new character, which in turn throws off the count completely as it will never return the correct result after this. Deleting all chars one at a time results in a final count of 1 when it should in fact be empty (as 0 is a valid number).

Not very helpful when you're trying to determine if a certain state contains a minimum amount of chars OR is empty - which in this scenario it never would be. I know there are other ways to check the data but I've just discovered this and thought it was worth mentioning.

Working demo

example

spice
  • 1,442
  • 19
  • 35
  • I don't think this is a duplicate. The count of length is being incorrectly `incremented` by a delete keypress. Unless React just counts every keypress as a new character in the state no matter what it is? And if that is the case, surely this is buggy no? – spice Oct 30 '18 at 22:56
  • Excuse me, I understood it as the length not updating since you checked it synchronously right after `setState`. If you can create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) we can open up the question again. – Tholle Oct 31 '18 at 00:14
  • Just added a fiddle to demonstrate what I mean. – spice Oct 31 '18 at 02:06
  • Thanks. I'm not sure how to recreate your issue. If I write `things` is rightly displays length `6`, and if I remove a character so it becomes `thing` it displays length `5`. – Tholle Oct 31 '18 at 09:32
  • Did you open the console log on that fiddle? You should see the count increase in the console when you first hit delete. https://ibb.co/gUaiXf – spice Oct 31 '18 at 12:57
  • Yes, that's because of the nature of asynchronous `setState` and why I tagged this question as a duplicate. You can't use `this.state` right after `setState` since it has not been updated yet. Use it in the callback if you must. `this.setState({ stuff: e.target.value }, () => { console.log('[Length of Stuff is]:', this.state.stuff.length); });` – Tholle Oct 31 '18 at 13:09

0 Answers0