I have been trying to render information from my firebase to a react native component. I started by console logging what I have done, the data is being fetched completely fine:
displayAllPlayers(){
dbh.collection('Players').get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.data().First, doc.data().Last)
})
})}
I then tried to add this information to my component as follows:
displayAllPlayers(){
dbh.collection('Players').get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
<Player key={doc.data().First} fName={doc.data().First} lName={doc.data().Last} />
})
})
}
render() {
const myPlayers = this.displayAllPlayers()
}
return(
{myPlayers}
)
You should return the JSX inside the render
function.
displayAllPlayers
isn't returning anything.
In this snippet
querySnapshot.forEach(doc => { <Player key={doc.data().First} fName={doc.data().First} lName={doc.data().Last} /> })
you're not returning anything inside the callback passed to forEach
even if you do, it doesn't work because forEach
doesn't return an array. You can use map here.
Maintain a state in the component and update it once you get the data. Use this state for rendering the array of JSX elements.
It's always suggested to create a different helpers file.
Create a firebase-helpers.js
file which has an function to convert snapshot to array.
// FILENAME - firebase-helpers.js
export const snapshotToArray = (snapshot) => {
let returnArr = [];
snapshot.forEach((childSnapshot) => {
let item = childSnapshot.data();
returnArr.push(item);
});
return returnArr;
};
Now in your screen, import this file
import { snapshotToArray } from "../helpers/firebaseHelpers";
Then, convert snapshot of Players to array
const playersSnapshot = dbh.collection('Players').get();
const playersArray = snapshotToArray(playersSnapshot);
this.setState({ players : playersArray });
Now in state you have an array players. To display content of Players, you can use in your render function as -
<FlatList
data={this.state.players}
renderItem={({ item }, index) => this.playerDisplay(item, index)}
keyExtractor={(item, index) => index.toString()}
/>
You can then have a function to return details of players as -
playerDisplay = (item, index) => {
return(
<View>
<Text>
Player {index} - {item.First} {item.Last}
</Text>
</View>
);
}
I hope it works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.