I've started learning developpment on React Native fairly recently and I've come accross a problem, I'm currently writing a registration system for an app using firebase, I want the user to choose a sports room using a picker and all the sports rooms available for choice are fetched from a firebase database.
My code is the following:
getPickerElements() {
var sportsRoomRef = firebase.database().ref('/sportsRoomList');
var snapshotList = new Object();
var pickerArr = [];
sportsRoomRef.once('value').then(snapshot => {
snapshotList = snapshot.val();
for (var key in snapshotList) {
pickerArr.push(<Picker.Item label={snapshotList[key]} value={snapshotList[key]}/>);
}
})
return (pickerArr);
}
And this is the picker I have in my view:
<Picker
selectedValue={this.state.pickerSelection}
style={[{width: 290, height: 50, color: 'black'}, pickerStyle]}
onValueChange={(itemValue) => this.setState({pickerSelection: itemValue})}>
<Picker.Item label='Salle de sport' value='default'/>
{getPickerElements()}
</Picker>
My issue is that, when returned, pickerArr does not contain anything because from what I've read .then() is asynchronous but it's not possible to use return within .then().
I've been stuck on this problem for quite some time now trying different things and I still haven't found a solution because of my lack of knowledge regarding React Native.
I have logged the contents of snapshotList and I can say for sure that data is getting correctly fetched from the database but I can't get the picker to display it. How can I fix this?
One way to go about this is to decouple data fetching and presentation.
More specifically, putting snapshotList in the component state and trigger data fetch when the component gets mounted. This way, component will show nothing initially, but as soon as the data gets loaded it will re-render and show picker items.
Something along those lines, but can't be sure without seeing more of your code:
constructor() {
this.state = {
snapshotList: {},
};
this.getPickerElements = this.getPickerElements.bind(this);
}
componentDidMount() {
var sportsRoomRef = firebase.database().ref('/sportsRoomList');
sportsRoomRef.once('value').then(snapshot => {
var snapshotList = snapshot.val();
this.setState({snapshotList});
})
}
getPickerElements() {
var pickerArr = [];
var snapshotList = this.state.snapshotList;
for (var key in snapshotList) {
pickerArr.push(<Picker.Item label={snapshotList[key]} value={snapshotList[key]}/>);
}
return pickerArr;
}
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