Reputation: 3
I have a function from where I want to return JSX. I´m new to React, I tried this: history is array of objects and I want to return text from it and display it.
renderCard = () => { const db = firebase.firestore();
db.collection("users")
.doc(firebase.auth().currentUser.uid)
.collection("userRequestDeposit")
.get()
.then(snapshot => {
let history = snapshot.docs.map(doc => {
const data = doc.data().request;
return { ...data };
});
history.forEach(elem => {
return (
<View>
<Text>{elem.data}</Text>
</View>
);
});
});
};
Upvotes: 0
Views: 286
Reputation: 1726
So this is a nice case study for how to use React.
You want to fetch this data when the component mounts. When you have the data, you will update the component's state. You can then render the output from that state.
Here is how you could do this with your code:
import {useEffect, useState} from 'react';
const YourComponent = () => {
const [history, setHistory] = useState([]); // Store your data in this state
// this useEffect will run only once (when the component mounts).
useEffect(() => {
db.collection('users')
.doc(firebase.auth().currentUser.uid)
.collection('userRequestDeposit')
.get()
.then(snapshot => setHistory(snapshot.docs.map(doc => ({...doc.data().request}))));
}, []); // <-- the empty dependency array means it only runs on mount
// when history is updated, you can map over the array and render the output here
return history.map(item => (
<View key={item.id}>
<Text>{item.data}</Text>
</View>
));
};
or as a class component...
import {Component} from 'react';
class YourComponent extends Component {
state = {
history: [],
};
componentDidMount() {
db.collection('users')
.doc(firebase.auth().currentUser.uid)
.collection('userRequestDeposit')
.get()
.then(snapshot => {
this.setState({history: snapshot.docs.map(doc => ({...doc.data().request}))});
});
}
render() {
return history.map(item => (
<View key={item.id}>
<Text>{item.data}</Text>
</View>
));
}
}
Upvotes: 1