Shows empty data using rn picker select in react native

845 Views Asked by At
const [country, setCountry] = useState([]);

useEffect(() => {
DataService.get(API.API_GET_COUNTRY).then((response) => {
  console.log('Countries', country);

  // let data = response.data.items;
  //   data.map(names=>{console.log("name",names['name'])
  //   let piker=[]
  //   piker.push({label:names['name'],value:names['id']})
  //   console.log("Picker",piker);
  // })

  setCountry([response.data.items]);
});
 }, []);

function getPickerItems(array, labelKey, valueKey) {
 const pickerItems = [];
 array &&
array.map((item) =>
  pickerItems.push({ label: item[labelKey], value: item[valueKey] })
);
return pickerItems;
 }

 <RNPickerSelect items={getPickerItems(country, 'name', 'id')}/>

// I was trying to show the list of countries name in picker select. I get response from the api and set in the country state. Since that i get array of data. But i am not able to see data in picker. Please help me out to solve this problem.

1

There are 1 best solutions below

1
On BEST ANSWER

The way you code is written, each time a component is rerendered getPickerItems function once again has to go over list of countries fetched from server to format it according your needs. But you actually don't need this, if you adjust your state so that it closely follows the view model (used by RNPickerSelect):

const [countries, setCountries] = useState([]);

useEffect(() => {
  DataService.get(API.API_GET_COUNTRY).then((response) => {
    const fetchedCountries = response.data.items.map(item => {
      return {
        label: item.name,
        value: item.id
      };
    });
    setCountries(fetchedCountries);
  });
}, []);

... and then just pass this state into RNPickerSelect:

<RNPickerSelect items={countries} />