sickdyd / react-search-autocomplete

A search box that filters the provided array of objects
https://sickdyd.github.io/react-search-autocomplete
MIT License
218 stars 82 forks source link

How to change the items based on the search string and call the API? #50

Closed yanffz closed 2 years ago

yanffz commented 2 years ago

Hi,

I will need to change the items based on the search string and call the API. For example, when I type "cof", I will need to pass the search string "cof" to an API and get the results from the API and set the results to items. When I type "cha", I will need to pass the search string "cha" to an API and get the results from the API and set the results to items.

May I know how to do it? Thanks!

sickdyd commented 2 years ago

@yanffz Hello! All you need to do is to add a handler for onSearch where you use something like fetch to send the request to the API and then pass the new items to RSA. A rough example:

  const [items, setItems] = useState([])

  const handleOnSearch = async (string, results) => {
    await fetch(`api/endopoint?search=${string}`)
      .then(response => response.json())
      .then(data => setItems(data))
  }

  // in the render method
  <ReactSearchAutocomplete
    items={items}
    onSearch={handleOnSearch}
  />

Said that, what does the first API call do? Is it searching for a string? If so, you are basically sending a search query to an endpoint, getting some results, putting them in RSA then searching again within RSA; it's a bit weird. Ideally RSA should have a single list that needs to be searched in. I think that what you need is just a normal select element that shows the list of items you get from the API.