Reputation:
I am facing a problem with adding the data to picker.item for which the data is in the form of a single array.
I have tried using the map and push for the array, but nothing seems to be working.
My array is as follows
[ "ABC", "XYZ", "123", "aaa"]
class XYZ extends Component {
constructor(props) {
super(props);
this.state = { statelist: '' };
list() {
fetch('myURL', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
return response.json();
})
.then((data) => {
data.map((item,key)=>{
console.log(item,key,'item and key')
return(
<Item label={item} value={item} />)
})
}
async onStateChange(value) {
await this.setState({
statelist: value
});}
render() {
return (
<View >
<Picker
selectedValue={this.state.abc}
onValueChange={this.onStateChange.bind(this)}>
this.list()}
</Picker>
</View>
);
};
}
export default withNavigation(XYZ);
I want a dropdown consisting of 5 options as shown above which should be all the 5 elements of the array.
Upvotes: 0
Views: 362
Reputation: 6446
You are not returning the data from your call, and you are also handling an async call. You should get the data on each render, or once in componentDidMount()
, and set the state.
const DATA = [1, 2, 3, 4, 5, 6]
class Select extends React.Component {
constructor() {
super()
this.state = {}
}
getList() {
return Promise.resolve(DATA).then(data => data.map(item => <option label={item} value={item} />))
}
componentDidMount() {
this.getList().then(data => this.setState({ list: data }))
}
render() {
return (
<select onChange={this.onStateChange}>
{this.state.list || null}
</select>
)
}
}
ReactDOM.render(
<Select />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1
Reputation: 411
here you can find a sample of what I meant using state of component.
https://codesandbox.io/s/sample-select-from-array-190823-u1oux
Upvotes: 0
Reputation: 411
In order to trigger an update on the component to add items, in your case you should use React state. In fact, using fetch you are doing an asynchronous operation that does not return immediately the result.
In your then()
callback in the fetch, you save data
into a state variable if you use hooks in function components ( look this link: https://reactjs.org/docs/hooks-reference.html#usestate ), or using this.setState({data: data})
if you use class components.
Then in the return statement, you use the data
variable (for function components):
return <Picker>
{ data.map((item)=> <Item label={item} value={item} />) }
<Picker>
or in render
method (for class components):
<Picker>
{ this.state.data.map((item)=> <Item label={item} value={item} />) }
<Picker>
In any case, I can help you better if you share your file, otherwise I cannot write a complete example.
Upvotes: 0