user3637804
user3637804

Reputation: 177

How to make search faster using Debounce Lodash React Native

How can I make my search faster using debounce? Right now the search works but its loading pretty slow. I imagine its because its searching every time a key is pressed. I looked at the other examples and I am having trouble applying it to my own scenario. I call my filter method on onChangeText inside the AutoComplete component which is inside my Main component. How can I debounce this for my scenario, as I need to pass in the text im filtering.

SEARCH

  filterRooms = (text) => {
    const { rooms } = this.state;
    if(text && text.length > 0) {
      newSearch = rooms.filter(room => room.toLowerCase().includes(text.toLowerCase()))
  }

  // set the state
  this.setState({ rooms: newSearch, query: text, hideResults: false });

  }
}

AUTOCOMPLETE

<Autocomplete
          data={this.state.rooms}
          defaultValue={query}
          hideResults={ hideResults }
          onBlur={ () => this.setState({ hideResults: true }) }
          onFocus={ () => this.setState({ hideResults: false }) }
          onChangeText={ text => this.filterRooms(text) }
          renderItem={item => (
            <TouchableOpacity onPress={() => this.setState({ query: item })}>
              <Text>{item}</Text>
            </TouchableOpacity>
          )}
        />

Upvotes: 0

Views: 867

Answers (1)

Akrion
Akrion

Reputation: 18525

As a start I would suggest to have a min characters required to begin the auto complete searches. Why start at 1 char? Usually this is set to 2.

After that you can just wrap filterRooms with _.debounce:

constructor(props) {
    super(props);
    this.filterRooms = _.debounce(this.filterRooms, 1000);
}
filterRooms = (text) => {
    const { rooms } = this.state;
    if(text && text.length > 0) {
        newSearch = rooms.filter(room => room.toLowerCase().includes(text.toLowerCase()))
    }
}

Upvotes: 1

Related Questions