简体   繁体   中英

How to make autocomplete faster and smoother in React/Redux?

I've implemented a search bar with autocomplete.

The input component has an onChange property that triggers off an action creator that makes a GET request to my DB to fetch autocomplete suggestions.

I'm then returning and rendering the entire action.payload each time.

onInputChange :

onInputChange(event) {
    this.setState({ term: event.target.value });

    if (event.target.value.length >= 3) {
      setTimeout(this.props.fetchSuggestions(event.target.value), 1000);
    }
  }

fetchSuggestions (action creator):

export const fetchSuggestions = (term) => async dispatch => {
  const res = await axios.get(`${BASE_URL}/api/symptoms?query=${term}`);

  dispatch({
    type: constants.FETCH_SUGGESTIONS,
    payload: res.data
  });

}

symptomSuggestions (reducer):

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_SUGGESTIONS:
      return action.payload;
    default:
      return state;
  }
}

At the moment I've limited queries to length 3 or more and querying every 1s to limit the API calls I make to the database.

Given this implementation, are there any other ways I can improve the autocomplete feature to make it less laggy?

You can try to add some debounce. Something like:

let lastFetched = 0;

onInputChange(event) {
  this.setState({ term: event.target.value });

  if (event.target.value.length >= 3 && (new Date() - new Date(lastFetched )) > 300) {
    lastFetched = Date.now();
    this.props.fetchSuggestions(event.target.value);
  }
}

This way you woun't be sending request every time that user types every single character, but only after slight period, after he finished typing.

可能矫kill过正,但是RxJS(又名Redux-observable)已经消除了内置的抖动,以及许多其他可以节流的运算符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM