1

I have a feature that uses React-Autosuggest to search through a small amount of data, all stored in memory once fetched from the backend. In other words, after the initial bulk fetch, there are no more network calls to power search.

The function I call when the search box calls onSuggestionsFetchRequested naively looks through this.props.dataset to return search suggestions.

    <Autosuggest
      ...
      onSuggestionsFetchRequested={({value}) => {this.setState({currentSearchSuggestions: this.getSuggestions(value)});}}
      ...
    />
    getSuggestions(rawValue) {
      const toSearchThrough = Object.values(this.props.dataset);
      ...
    }

However, if the user enters a search before this.props.dataset is populated, no suggestions show even after the data loads up, until the user changes their input slightly, causing getSuggestions to be invoked again.

Is there something clever I can do to block getSuggestions until the dataset is ready? Again, this is something that only happens once each page load.

Antrikshy
  • 2,918
  • 4
  • 31
  • 65

2 Answers2

0

Can you prevent the component from rendering until there's data? If dataset is an empty object you'll have to check it's length, but something like this:

{this.props.dataset && (
   <Autosuggest ... />
)}
Duderino9000
  • 2,535
  • 4
  • 31
  • 37
  • Yeah, as a workaround, I have resorted to disabling the input by passing in an `inputProps` value conditionally. But given the way my users use the search bar, the ideal experience would allow them to start typing or pasting in a value *while* the data is loading and have the dropdown show when the data is ready so they don't have to wait the few seconds. – Antrikshy Dec 09 '19 at 18:52
0

I think this can solve your problem.

componentDidUpdate(prevProps) {
  // Assume this.state.searchQuery is set on user input via onChange defined in Autosuggest inputProps
  if (this.state.searchQuery && this.props.dataset !== prevProps.dataset) {
    this.setState({currentSearchSuggestions: this.getSuggestions(searchQuery)});}
  }
}
Antrikshy
  • 2,918
  • 4
  • 31
  • 65
think-serious
  • 1,229
  • 2
  • 12
  • 27
  • 1
    Wow, I was thinking too much into `onSuggestionsFetchRequested` and assumed that Autosuggest _had_ to call it for it to work, forgot that there's a `suggestions` prop right there that I can populate whenever. This works perfectly! – Antrikshy Dec 09 '19 at 22:23
  • 1
    I've submitted some updates (apparently for peer review) based on my actual implementation for posterity. Most importantly, I shouldn't compare current state to prevState. Only the prop comparison is useful here, and running this logic on state change actually breaks things. – Antrikshy Dec 09 '19 at 22:28