1
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.

Akash
  • 29
  • 6
  • 1
    Why do you wrap `response.data.items` in another array in `setCountry` call? Otherwise, it should work. – raina77ow Jun 19 '21 at 10:36
  • Sorry my mistake. I run around all the other things to solve my problem. Thank you so much for your help. – Akash Jun 19 '21 at 10:43

1 Answers1

1

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} />
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Thank you for your help friend. Actually that function is called from another component, in order to make my work easy by simply calling the function. – Akash Jun 19 '21 at 10:46