Populate ReactNative ListView with Firebase data - firebase

I've been struggling for a few days to get this working. I want to populate a ListView in React Native with data from my Firebase database. I have this setup:
const ListItem = require('./profileRow');
var database = firebase.database();
var userId, dataKey;
class Selection extends Component {
constructor(props) {
super(props);
userId = firebase.auth().currentUser.uid;
this.dataRef = firebase.database().ref('/users/' + userId + '/profiles_info');
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
};
}
listenForProfiles(dataRef){
dataRef.on('value', (snap) => {
var profiles = [];
snap.forEach((child) => {
profiles.push({
name: child.val().forename,
_key: child.key
});
});
alert(profiles);
this.setState({
dataSource: this.state.dataSource.cloneWithRows(profiles)
});
});
}
componentDidMount() {
this.listenForProfiles(this.dataRef);
}
render() {
return (
<Image source={require('../assets/bg.png')} style={styles.container}>
<View style={{flex: 1, flexDirection:'column'}}>
<Text>
Select a profile to view:
</Text>
</View>
<View style={{flex: 1}}>
<ListView dataSource={this.state.dataSource} renderRow={this._renderItem.bind(this)} enableEmptySections={true} style={styles.listview}> </ListView>
</View>
</Image>
);
}
_renderItem(item) {
return (
<ListItem item={item}/>
);
}
}
The datastructure looks like this:
So what I'm trying to do here is populate each row of the ListView with the "forename" String of each "profile" directory (0,1,2).
But on my alert() I am returned: [object Object],[object Object],[object Object] which must mean it is only fetching the directories as Objects from "profiles_info" and not each "forename" String from those directories.
This is where I am stuck, I hope someone can shed some light on this. I know what the solution should be, I just don't know how to apply it in code.
Thanks in advance!

You are pushing objects into your profiles array here, so it makes sense that your alerts are showing objects:
profiles.push({
name: child.val().forename,
_key: child.key
});
If you use alert(JSON.stringify(profiles)); instead of alert(profiles); you should see an array of objects with fields name and key. Accessing profiles[0].name would give the actual name.
Side note, if you use console.log instead of alert you get some more meaningful information.

Try Following Tutorial. may be help you.
react-native-firebase-tutorial-list

Related

this.props.route.params returns value as undefined

I'm building a barcode reader app that scans that qr code and then takes data and is used as a key to fetch an object from firebase. In order the data to be used as a key I need to pass through another screen but when I check console log it's cameback that the scanned key is undefined.
The itself barcode scanner works perfectly.
Barcode class :
export class BarCodeScannerScreen extends Component{
state = {
CameraPermissionGranted: null,
}
async componentDidMount() {
// Ask for camera permission
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ CameraPermissionGranted: status === "granted" ? true : false });
};
barCodeScanned = ({ data }) => {
//Access the Data
alert(data); // shows the scanned key
this.props.navigation.navigate('Info', {
item: data, }); // but then it's dissapears in here.
};
render(){
const { CameraPermissionGranted } = this.state;
if(CameraPermissionGranted === null){
// Request Permission
return(
<View style={styles.container}>
<Text>Please grant Camera permission</Text>
</View>
);
}
if(CameraPermissionGranted === false){
// Permission denied
return (
<View style={styles.container}>
<Text>Camera Permission Denied.</Text>
</View>
);
}
if(CameraPermissionGranted === true){
// Got the permission, time to scan
return (
<View style = {{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<BarCodeScanner
onBarCodeScanned = {this.barCodeScanned }
style = {{
height: DEVICE_HEIGHT/1.1,
width: DEVICE_WIDTH,
}}
>
</BarCodeScanner>
</View>
);
}
}
}
Here is my Info screen that receives the information :
export default class InfoScreen extends Component {
constructor(props){
super(props);
this.state={
productlist:[],
scannedkey: this.props.route.params.item
} }
async componentDidMount(){
firebase.database().ref(`product/${ this.state.scannedkey}`).on(
"value",
(snapshot) => {
var list = [];
snapshot.forEach((child) => {
list.push({
key: child.key,
title: child.val().title,
//details: child.val().details,
//price: child.val().price
});
});
this.setState({ productlist: list });
},
(error) => console.error(error)
);
}
componentWillUnmount() {
if (this.valuelistener_) {
this.valueRef_.off("value", this.valuelistener_)
}}
render() {
console.log(this.state.scannedkey); // console log shows that scanned key is undefined
return(
<View style={styles.container}>
<Text>Hey</Text>
<Text>{this.state.productlist.title}</Text>
</View>
);}}
App.js
export default function App() {
const Drawer=createDrawerNavigator();
return (
<Provider store={store}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Barcode">
<Drawer.Screen name="Barcode" component={BarCodeScannerScreen} />
<Drawer.Screen name="Info" component={InfoScreen} />
</Drawer.Navigator>
</NavigationContainer>
</Provider>
);
}
I ussualy use function components to navigate through but with class components it's a little tricky for me. Perhaps I missed something?
So far I 've tried :
this.props.navigation.navigate('Info', {
item: JSON.stringify(data) , });
And it didn't work.
I will be grateful for your help.
Try to use item directly from props, not from state
in your componentDidMount call where you supply from state the scannedKey, supply it from props
firebase.database().ref(`product/${this.props.route.params.item}`)....
you are also calling this.props instead of props directly in your state inside your constructor, which have direct access to it, that's why you can call super(props) and not super(this.props), I am not sure if this is the issue, but in react docs says don't copy props to state because they get ignored, and it's bad practice my friend.
check this link, in the big yellow note what I am reffering to
https://reactjs.org/docs/react-component.html#constructor

mapping firebase read to props react-native

this might not be an issue with the mapping itself but i've read some data from my firebase realtime database into my sate and i'm trying to pass it as props then map it in a subsequent component.
I am getting the following error, I am using an android emulator:
TypeError: undefined is not a function (near ...'this.props.notes.map'...)
app.js (where I update the state)
state = {
loggedin: false,
notes: [
{
id: 1,
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
id: 2,
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
}
//passing props to notes component
<Notes style={styles.notes} notes={this.state.notes} />
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
my Notes component where I map the props
renderCondition =()=>{
if(this.state.Deleted === false){
return(
<View>
{this.props.notes.map(note => (
<View
style={styles.note}
key={note.author}
id={note.id}
>
<Text style={styles.noteHeader}>{note.author}</Text>
<Text style={styles.noteText}>{note.text}</Text>
<Text style={styles.noteTime}>{note.time}</Text>
<Button title= 'X' onPress={() => this.setState({Deleted:true}) }></Button>
</View>
))}
</View>
)
}
return(
<View>
<Text>are you sure you want to delete this note?</Text>
<Button title="Yes"></Button>
<Button onPress ={()=>{this.setState({Deleted:false})}} title="No"></Button>
</View>
)
}
render() {
return (
<View>
{this.renderCondition()}
</View>
);
}
You have to check whether the notes have been passed down or whether they are undefined or null. JavaScript is not going to map an undefined object.
Try the following code:
{this.props.notes && this.props.notes.map(note => (
// do stuff with each note...
))}
This will run the .map function only if the notes are neither undefined nor null.
So my issue was that I needed to update my notes state by making sure it was an array. I had mistakenly simply updated it as an object and then attempted to map the object. Here is my solution.
from this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
to this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: [snapshot.val()] });
};

Fetch data in flat list from Firebase Real Time Database

I have a structure of data i want to fetch and display in a Flat List here is my data.
-Lt10FlMt0xtru36Ztmb
name : "Hello"
-Lt0pdC5Ikwd-ZWNBiYJ
name : "Coke"
-Lt0paPi_-zkCelfoisM
name : "Pespsi"
Here is my code:
readUserData = () => {
firebase.database().ref('Brands/').once('value').then((snapshot) => {
console.log(snapshot.val())
const userdata = snapshot.val();
// Alert.alert("Helo" , userdata);
this.setState({
getListbrands : userdata
})
Alert.alert("Data" , JSON.stringify(this.state.getListbrands))
});
}
and here i am setting data in Flat list but it is not showing any thing please guide.
{
this.state.getListbrands &&
<FlatList
data={this.state.getListbrands}
keyExtractor={(a, b) => b.toString()}
renderItem={({ item }) => (
<Text style={{color:'#000'}}>{item.name}</Text>
)}
/>
}
According to the documentation, FlatList component expects an array of data. The value of your snapshot is an object, and not an array.
If you want to use an array of the values of each child node, you can get that with:
firebase.database().ref('Brands/').once('value').then((snapshot) => {
userdata = [];
snapshot.forEach((child) {
userdata.push(snapshot.val());
})
...
You can then set this array to the FlatList.
{
this.state.getListbrands &&
<FlatList
data={this.state.getListbrands}
keyExtractor={(a, b) => b.toString()}
renderItem={(item) => (
<Text style={{color:'#000'}}>{item.name}</Text>
)}
/>
}
change like this.i think item in here is not a object.please try. it will work. thank you.

Rendering data in FlatList from firebase

I am using React Native 0.49. I have data fetched from firebase, list of users users/, each item in this list was set like this firebase.database().ref('users/' + userId).set(userInfo) userId is the uid of the currentUser.
Now I am fetching back (in actions - redux):
export function getPeople(){
return (dispatch) => {
dispatch(getPeopleRequest());
getData().then(result => {
dispatch(getPeopleSuccess(result.val()))
})
.catch(error => {
dispatch(getPeopleFailure(error))
});
}
}
const getData = () => {
const userRef = firebase.database().ref('users/').limitToFirst(20);
return userRef.once('value');
}
In component, I am trying to render the data in FlatList, but it's not rendering anything, I don't know what I'm doing wrong:
componentDidMount(){
this.props.getPeople();
}
_renderItem = ({ item }) => (
<View style={{flex: 1}}>
<Text>{item}</Text>
</View>
);
render(){
const { inProgress, people, error } = this.props.peopleData;
return (
<FlatList
data={people}
renderItem={this._renderItem}
/>
);
}
when console log people this is result:
{cpycwkz7exVBzmhaLEtHjMW66wn1: {…}, UbIITfUANmb63cYE2x7dZRZ0pfK2: {…}}
FlatList component expects its data prop to be an array. You are passing it as an Object. You can change it to an array of Objects. Then too in your _renderItem method the item will be an object and it can't be rendered straight away in <Text>, you have to extract a text value from the item object and than render it as: <Text>SOME_TEXT_NOT_AN_OBJECT</Text>
You can convert your people object to an array and pass it to the <FlatList like this:
render(){
const { inProgress, people, error } = this.props.peopleData;
let ArrayOfPeopleObject = Object.values(people)
return (
<FlatList
data={ArrayOfPeopleObject}
renderItem={this._renderItem}
/>
);
}
Now each item in the _renderItem method will be an object and you can extract value from any key and render it in the <Text>.
Flatlist data requires a key for each object in the array you can convert the firebase result like this:
Object.entries(peopleFromFirebase).map(item => ({...item[1], key: item[0]}));
So json from firebase like this:
{
cpycwkz7exVBzmhaLEtHjMW66wn1: {
name: 'wade owen watts',
phone:'+447...'
},
UbIITfUANmb63cYE2x7dZRZ0pfK2: {
name: 'Helen Harris',
phone:'+448...'
}
}
becomes:
[
{
key: 'cpycwkz7exVBzmhaLEtHjMW66wn1',
name: 'wade owen watts',
phone:'+447...'
},
{
key:'UbIITfUANmb63cYE2x7dZRZ0pfK2',
name: 'Helen Harris',
phone:'+448...'
}
]
Flat list except array of objects but the firebase return the data as map like {key: value} pair so you should transform this map to array , you can install lodash module and use _.values() function to do that

React-Native - Firebase data in TextInput

I could retrieve data from Firebase and display it immediately after. But when I try to use it in render, it is blank. I am new to react-native and might be doing something incorrect. How can I use data from Firebase in render ?
Here is my code:
componentWillMount() {
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var DisplayEmail = snapshot.val().Email; alert(DisplayEmail);
});
}
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus = {true}
autoCorrect = {false}
autoCapitalize = "none"
placeholder={this.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}
Whenever you want to have something display on render, you should put it on state. By changing the state, you would cause the page to re-render and be updated with the new state. So when you do your firebase call, add it to state.
componentWillMount() {
firebase.database().ref('/users/' + userId).on('value', snapshot => {
this.setState({ DisplayEmail: snapshot.val().Email });
});
}
Calling set state just merges your state changes with your current state. Now you should be able to call state from render and have it work.
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus={true}
autoCorrect={false}
autoCapitalize="none"
placeholder={this.state.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}
it must be work :)
componentWillMount() {
firebase.database().ref('/users/' + userId)
.on('value', snapshot => {
this.state = { DisplayEmail: snapshot.val().Email
});
}
render() {
return (
{alert(this.props.DisplayEmail)}
<TextInput style={styles.input}
autoFocus = {true}
autoCorrect = {false}
autoCapitalize = "none"
placeholder={this.state.DisplayEmail}
keyboardType="email-address"
underlineColorAndroid='transparent'
editable={false}
/>
)
}

Resources