Search code examples
javascriptreactjsasynchronoussearch-suggestion

How can I pause a React-Autosuggest search until after async data is ready?


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.


Solution

  • 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)});}
      }
    }