React-autosuggest: onSuggestionsFetchRequested for async fire too many times

Created on 25 Jan 2019  路  2Comments  路  Source: moroshko/react-autosuggest

This is not a bug but I have a question. Right now I have this code for fetching async suggestion source from api

onSuggestionsFetchRequested = async ({ value }) => {
    console.log(value)
    try {
      const { results } = await getSuggestionszAPI(value)
      this.setState({
        suggestions: getSuggestions(results, value)
      })
    } catch (error) {
      console.log(error)
    }
  }

the problem is this function trigger every time the user focus on the input, how to avoid firing the same call? it should only call only if the input value is changed by the users.

Most helpful comment

You should probably use the reason:

onSuggestionsFetchRequested({ value, reason })

All 2 comments

You should probably use the reason:

onSuggestionsFetchRequested({ value, reason })

e.g. with React 16.8 and non-async -

  function onSuggestionsFetchRequested({ value, reason }) {
    if (reason === 'input-changed') {
      setSuggestions(getSuggestions(value))
    }
  }
Was this page helpful?
0 / 5 - 0 ratings