I am getting my document data back and storing it in state, but when I try to render it, I am only getting the first item. I notice when I refresh the app, I can see the other items briefly. Not sure why my mapping isn't rendering all the data.
const [tickets, setTickets] = useState([]);
useEffect(() => {
GetTickets();
}, []);
console.log(tickets);
const db = getFirestore();
const colRef = collection(db, "Tickets");
function GetTickets() {
getDocs(colRef).then((snapshot) => {
let tickets = [];
snapshot.docs.forEach((doc) => {
tickets.push({ ...doc.data(), id: doc.id });
setTickets(tickets);
});
});
}
return (
<View style={GlobalStyles.container}>
<Text>Previous tickets</Text>
{tickets.map((ticket) => (
<Text key={ticket.id}>{ticket.form.TicketNumber}</Text>
))}
</View>
);
In React Native, you can use map or flatList for rendering an array. If you are trying to display a large amount of data it is better to use flatList(better performance with large amount of data).
Replace this code
{tickets.map((ticket) => (
<Text key={ticket.id}>{ticket.form.TicketNumber}</Text>
))}
with this code
<FlatList
data={tickets}
renderItem={({item}) => <Text>{item.form.TicketNumber}</Text>}
/>
Try this may be your state is getting set before your data is pushed in array put it outside loop like this
const [tickets, setTickets] = useState([]);
useEffect(() => {
GetTickets();
}, []);
console.log(tickets);
const db = getFirestore();
const colRef = collection(db, "Tickets");
function GetTickets() {
getDocs(colRef).then((snapshot) => {
let tickets = [];
snapshot.docs.forEach((doc) => {
tickets.push({ ...doc.data(), id: doc.id });
});
setTickets(tickets);
});
}
return (
<View style={GlobalStyles.container}>
<Text>Previous tickets</Text>
{tickets.map((ticket) => (
<Text key={ticket.id}>{ticket.form.TicketNumber}</Text>
))}
</View>
);
I'm not sure if it will help you but 2 comments for help you in your search:
Hope it can help you.