Jarek N
Jarek N

Reputation: 55

React-select does not render data

I'm trying to use react-select to make a simple dropdown menu, with values from public API. However, even though the fetch from API appears to be working correctly (console.log() shows the desired data), there are no options in the dropdown selection.

I've tried following this thread thread

But since I wanted to use hooks, I had to make some changes.

I used the third approach from the top comment in the thread (the one where you pass labelKey and valueKey as a prop, instead of creating a new array), but the dropdown is just full of empty fields.

Here's an example of the data from API

"results:[
 {"name":"Algeria","code":"DZ","cities":1,"locations":1,"count":1149},
 {"name":"Andorra","code":"AD","cities":2,"locations":3,"count":80963},
 {"name":"Argentina","code":"AR","cities":1,"locations":4,"count":14976}
]

And here's the code for the actual function

function SearchBar(props) {
  const [options, setOptions] = React.useState([]);

  function handleChange(e) {
    props.setCountryName(e.value);
    }

    useEffect(() => {
      async function FetchData() {
        fetch(`https://api.openaq.org/v1/countries?limit=300`, {mode: 'cors'})
          .then(res => res.json())
            .then(
            (result) => {
              setOptions(result.results)
            })
          }   
          FetchData()   
      }
    ,[])  

    console.log(options);

  return(
    <Select
    className='react-select-container'
    placeholder="Choose country" 
    onChange={handleChange}
    labelKey="name"
    valueKey="code"
    options={options}
    />
  )
}

Upvotes: 2

Views: 834

Answers (1)

Sandeep Ranjan
Sandeep Ranjan

Reputation: 834

In react-select you need to tell which one the label and which is the value. If you do not have explicitly label and value in the options array.

<Select
    className='react-select-container'
    placeholder="Choose country" 
    onChange={handleChange}
    labelKey="name"
    valueKey="code"
    getOptionLabel={option => {
          return option.name;
        }}
    getOptionValue={option => {
          return option.code;
        }}
    options={options}
 />

Upvotes: 2

Related Questions