Reputation: 15
I am making a blood bank app and i am experiencing a problem in which I can't map my list of data in react native JSX. I copied most of the code from my todoApp that I made in react native earlier and modified it. I also want it to get all the data automatically when a user opens the app instead of manually using a button.
APP.JS:
import React from 'react';
import {Button,Text, View, ScrollView} from 'react-native';
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
list: [],
}
}
work=()=>{
firebase.database().ref().once('value').then(snapshot => {
var snap = snapshot.val();
var newStateArray = this.state.list.slice();
newStateArray.push({id: this.state.list.length + 1,username: snap.username, age: snap.age, bloodtype: snap.bloodtype, phonenumber: snap.phonenumber});
this.setState({list: newStateArray,});
});
}
render(){
return(<>
<ScrollView style={{ backgroundColor: 'white', marginVertical:20 }} showsVerticalScrollIndicator={true}>
<View>
{this.state.list.map(item => (<>
<View key={item.id} style={{borderBottomColor: 'black',borderBottomWidth: 5, marginBottom: 20}}>
<Text style={{fontSize: 22}}>{item.username}, {item.age}, {item.phonenumber}, {item.bloodtype}</Text>
</View>
</>))}
</View>
</ScrollView>
<View style={{position: 'absolute', bottom: 1, left: 1, right: 1,}}>
<Button title="test" onPress={this.work} />
<Button title="Go to My Profile" />
</View>
</>)
}
}
This is made in react native CLI. I will be very grateful for your help.
Upvotes: 0
Views: 171
Reputation: 602
Probably, you app is trying to fetch the data before the database is totally initialized. The best pratice is putting the
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
In the index.js
of your project. In your index.js
file put write
componentDidMount() {
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
}
In the App.js
file write:
componentDidMount(){
this.work()
}
Upvotes: 2