AliRehman7141
AliRehman7141

Reputation: 993

How can I check the TextInput change completed in react native

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.

Upvotes: 0

Views: 4763

Answers (2)

Sakkeer A
Sakkeer A

Reputation: 1100

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 COMPONENT:

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

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

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

FUNCTIONAL COMPONENT:

 function MyComponent(props) {
   const onTextChange = (text) => {
     console.log(text)
   };

   const _onTextChangeHandler = _.debounce(onTextChangeHandler, 1000, []);

    return <Input onChangeText={_onTextChangeHandler} />

 }

Upvotes: 1

RodSarhan
RodSarhan

Reputation: 1457

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

Upvotes: 3

Related Questions