'autocomplete suggestion for a search field by retrieving data from api

I am trying to get suggestions on a search field anytime the input field changes. However i keep running into various errors. this is what i've got so far.

  export default function AutoComplete() {

      const [info, setInfo] = useState([{'username': 'add a search word'},])
      const [search, setSearch] = useState()


      const handleChange = (e) => {
        setSearch(e.target.value)
      }


      useEffect(() => {

    const findItem = async (searchString) => {

        const response = await fetch('http://localhost:8000/' + searchString, {
        method: 'GET',
        headers:{
            'content-type': 'application/json',
        },
    })

        let data = await response.json()
        data = JSON.stringify(data)
        return data
    
      }

    if (search){
      var newdata = findItem(search)
      setInfo(newdata)
    }
    else {
      setInfo([{'username': 'add a search word'}])
    }

    
      }, [search])


  return(
  <div>
    <input onChange={(e) => handleChange(e)}></input>
    {info.map((suggestion) => {
      return (
        <div>
          {suggestion.username}
        </div>
      )
    })}
  </div>)
}

The error i am running into at the moment is 'info.map is not a function' when i try to type in the input field. I decided to do my own implementation after i spent a lot of time running into this same error when i was using the material ui implementation https://mui.com/components/autocomplete/. in their implementation, they have a variable storing the data rather than calling an api and it works well. I can see that my data is being retrieved as it pops on on console.log at the end of the findItem function. Please help!



Solution 1:[1]

It seems that your findItem function is returning a JSON string:

data = JSON.stringify(data)
        return data

Which is then set directly to the info variable:

setInfo(newdata)

This means that "info" will contain a JSON string rather than an array of JSON objects. Map doesn't work on JSON strings.

For your code to work you need to pass "setInfo" an array of objects; eg:

[
    {username: "John"},
    {username: "Amy"},
    {username: "Peter"}
]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob