0
constructor(props) {
        super(props);
        this.state= {
            input: "",
        }
    }
    _textChange = (text) => {
        this.setState({
            textValue: text,
            // textEntered: true
        })
        console.log(this.state.textValue);
    }

And:

<TextInput onChangeText={this._textChange}/>

I am able to print the text entered in TextInput to console. But when I am deleting the text from TextInput, then the first letter entered is still showing. I tried using clear(), but not able to do it. How do I clear this.state.input when text is deleted from TextInput.

CONSOLE

a
ab
abc
ab
a

As you can see, a still shows in console, even when everything is deleted from TextInput.

pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • 1
    I already closed as duplicate your **same** previous question few minutes ago, if you checked the duplicate answer you would notice the same mistake - you log a stale state as `setState` is async. You need to log `text` value or log the state in `componentDidUpdate` 1/2. – Dennis Vash Jan 09 '21 at 12:13
  • Or use the 2nd paramater of `setState`, you can check it in React docs at FAQ section or in the duplicate itself, again. 2/2 – Dennis Vash Jan 09 '21 at 12:13
  • @DennisVash Why are you in so much hurry to close the question!!! I am facing difficulty, that is why I am asking the question. And yes, I did saw the duplicate answer which you marked, but I am not able to understand it. I am very new to react-native. – pratteek shaurya Jan 09 '21 at 12:17
  • If you don't understand the answer, try asking about what you didn't understand - mentioning the sources you read. For the answer, aside my comment, try one of those: `console.log(text)` , `setState(...,() => console.log(this.state))`, or use a lifecycle. – Dennis Vash Jan 09 '21 at 12:25
  • @DennisVash Please read what I have asked. I want to clear my state, when text is deleted from `TextInput`. I also showed what I am able to see on console. For ex.: If I wrote "abc" in my `TextInput` and then delete everything from `TextInput`, my `this.state.input` still has "a", I want to clear this state when everything the deleted from `TextInput` – pratteek shaurya Jan 09 '21 at 12:29
  • Again - you log a stale state, the input is clear having inner value `""` but you having `"a"` in log which does not represent the input value. – Dennis Vash Jan 09 '21 at 12:39

1 Answers1

0

You are printing the textValue inside the _textchange function. The value doesn't change immediately. It will change the textValue after the whole function is executed completely.

 componentDidUpdate() {
    console.log(this.state.textValue)
 }

Add this snipper inside your class. This method will be executed whenever the state in your component changes...