Search code examples
reactjsreact-nativereact-native-textinput

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.


Solution

  • 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