简体   繁体   中英

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}
    />
  )
}

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}
 />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM