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>
);
CodePudding user response:
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>}
/>
CodePudding user response:
I'm not sure if it will help you but 2 comments for help you in your search:
- You are calling setTickets inside the loop, smells like a problem, because of the async flow.
- Also, why are you defining the variable name in the scope of the function, with the same name of the variable for state of the tickets, smells not so good.
Hope it can help you.