React dynamic Datalist - Options are not populated via api response

57 Views Asked by At

Please find the issue below.

Initially data will be empty array, so the loading option will be displayed in data list. But when the datalist is clicked, an api call will be made to get the data. Once the response is received from api, setData will be called with the response. Eventually datalist options should be updated with the response, but it is always showing loading itself. That loading is not removing at all.

Expected Behavior: datalist options should be auto populated with api response.

Current Behavior: datalist is always showing loading.

Below is the code for reference. Any solution would be greatly appreciated.

const DataList = () => {

  const [data, setData] = useState([]);
  const onClickHandler = async() => {
    const response = await fetchData(); //gets data from api
    setData(response);
  }

 return (
  <div className="custom-data-list-container">
     <input
       type="search"
       list="list"
       autoComplete="on"
       value={text}
       onChange={onChangeHandler}                
       onClick={onClickHandler}
       onBlur={onBlurHandler}
     />
     <datalist id="list" className="custom-data-list">
        {data.length > 0 ? ( // load options data
          <div>
            {data.map((d, idx) => (
              <option key={`${d}${idx}`} value={d} />
            ))}
          </div>
        ) : ( // show loading text
          <div>
               <option value=" "> Loading </option>
          </div>
        )}
     </datalist>
  </div>
)
}```
0

There are 0 best solutions below