Home > Software engineering >  How can I check the TextInput change completed in react native
How can I check the TextInput change completed in react native

Time:03-15

Basically, I need to hit search API when the text changed but it's not a good thing to call API on every change in TextInput. So, is there any callback function that exists in this Component that triggers when the user is done with editing (stopped typing)? That would be best if we trigger API when the user stops typing.

I have tried onEndEditing but it is not triggered after I stop writing.

CodePudding user response:

If you want to automatically detect when the user finishes editing you can do something like this

 const [value, setValue] = React.useState('');
 const timeout = React.useRef(null);

 const onChangeHandler = (value) => {
   clearTimeout(timeout.current);
   setValue(value);
   timeout.current = setTimeout(()=>{
      searchFunction(value)
   }, 2000);
 }

  return (
    <View>
      <TextInput
        value={value}
        onChangeText={ (value) => {onChangeHandler(value)} }
      />
    </View>

This will call the search function 2 seconds after the user finishes typing, and the duration will be refreshed whenever they type something

or you can try onBlur instead, those will trigger once the input is not focused anymore and won't trigger just cause you finished typing

CodePudding user response:

Please refer: https://stackoverflow.com/a/41215941/9315094

Also: https://stackoverflow.com/a/58594890/9315094

Debounce function should be defined somewhere outside of the render method since it has to refer to the same instance of the function every time you call it as opposed to creating a new instance like it's happening now when you put it in the onChangeText handler function.

The most common place to define a debounce function is right on the component's object. Here's an example:

class MyComponent extends React.Component {
   constructor() {
     this.onChangeTextDelayed = _.debounce(this.onChangeText, 2000);
   }

   onChangeText(text) {
     console.log("debouncing");
   }

   render() {
     return <Input onChangeText={this.onChangeTextDelayed} />
   }
 }
  • Related