I have a react native picker which has an array of objects that i have fetched from my API and saved to state under properties. This is a screenshot of my data fetched
I need to find the correct object in the array from the _id when I select the Property dropdown. I need this do be done using Javascript logic without making a second call to my server. This is my code inside the render for drop down
<View style={{margin: 20, flexDirection: 'row', flex: 1}}>
{/*PROPERTY....................................................*/}
<View style={{padding: '10px'}}>
<Picker style={styles.picker} selectedValue={this.state.pickerProperty}
onValueChange={(itemValue, itemIndex) => this.getPropertyById(itemValue)}>
<Picker.Item label="Select Property" value=""/>
{this.state.properties.map((item, key) => (
<Picker.Item label={item.PropertyName} value={item._id} key={key}/>
))}
</Picker>
{/*{this.getPropertyById()}*/}
</View>
{/*TYPE........................................................*/}
<View style={{padding: 10}}>
<Picker style={styles.picker} selectedValue={this.state.pickerType}
onValueChange={(itemValue, itemIndex) => this.setState({pickerType: itemValue})}>
<Picker.Item label="Select Type" value=""/>
{this.state.propById.map((item, key) => (
<Picker.Item label={item.tname} value={item.tname} key={key}/>
))}
</Picker>
<Text>{this.state.pickerType}</Text>
</View>
</View>
I need to write my code inside this function
getPropertyById=(itemValue)=> { //Need the code here
}
Found this solution and it helped me.
changeProperty(event) {
this.setState({selectedProperty: event.target.value});
this.setState({types: this.state.properties.find(property => property.PropertyName === event.target.value).Type})
}
changeType(event) {
this.setState({selectedType: event.target.value});
const Ty = this.state.properties.find(property => property.PropertyName === this.state.selectedProperty).Type;
this.setState({items: Ty.find(Typ => Typ.typename === event.target.value).Item})
}
Using each of these in onChange={} of each dropdown will solve the problem. Do not forget to modify your constructor as follows
constructor(props) {
super(props);
this.changeProperty = this.changeProperty.bind(this);
this.changeType = this.changeType.bind(this);
}