I have a picker in my app and i want to fill this with data fetched in the server, I have the data in a state of the app, but I don't know how to make the app to update the picker when the data is fetched
constructor(props) {
super(props);
this.state = {
isLoading: false,
client: '',
clients: null
};
}
componentDidMount() {
this.fetchData();
}
I have this in my view
<Picker
style={styles.picker}
itemStyle={styles.items}
selectedValue={this.state.client}
onValueChange={(cli) => this.setState({client: cli})}
prompt="Seleccione un cliente" >
<Picker.Item label="Cliente 1" value="1" />
<Picker.Item label="Cliente 2" value="2" />
<Picker.Item label="Cliente 5" value="5" />
<Picker.Item label="Cliente 4" value="4" />
<Picker.Item label="Cliente 3" value="3" />
<Picker.Item label="Cliente 9" value="9" />
<Picker.Item label="Cliente 8" value="8" />
</Picker>
and the fetchData function
fetchData() {
var baseURL = 'http://192.168.100.11:3000/clients';
fetch(baseURL, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.message){
this.setState({isLoading: !this.state.isLoading});
alert(responseData.message);
}else{
this.setState({isLoading: !this.state.isLoading, clients:responseData});
}
})
.done();
}
the thing is how can I make the picker update when the data is fetched. thanks
You should set the picker items based on your state by mapping them, for example:
<Picker style={styles.picker}
itemStyle={styles.items}
selectedValue={this.state.client}
onValueChange={(cli) => this.setState({client: cli})}>
{this.state.clients.map((l, i) => {return <Picker.Item value={l} label={"Cliente " + i} key={i} /> })}
</Picker>
When you receive the data from fetch, you just update the state of "clients", as you are doing, and the picker items will be updated automatically.
An example can be found here where the items are updated based on clicking the button: https://rnplay.org/apps/XfkfnQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With