I am using componentDidMount to show Firebase real-time data in a React-Native App, but, when I render first time, data is not being showed. I need to go back and navigate again into the page for the data to update and appear on screen. How can I solve this issue and show the data on first try ? Thank you.
export default class ForthPage extends Component {
constructor() {
super();
this.state = {
reservas: []
}
}
componentDidMount() {
const readUsersData = () => {
const nameRef = firebase.database().ref('user0001')
nameRef.on('value', (snapshot) => {
const state = snapshot.val();
this.state.reservas = state; //misstake(see my answer)
});
}
readUsersData()
const pushAdminData = (data) => {
this.setState({ data })
}
pushAdminData(this.state.reservas);
}
render() {
const reservas = JSON.stringify(this.state.reservas);
return (
<Background>
<View>
<ScrollView>
<Text> Mis reservas: {reservas}</Text>
</ScrollView>
</View>
</Background>
)
}
}
The calling of readUsersData()
function seems unclear.
Try defining function in same level as of render,componentDidMount.
Like below
constructor() {
super()
this.state = {
reservas: []
}
}
componentDidMount() {
const readUsersData = ()=> {
const nameRef = firebase.database().ref('user0001')
nameRef.on('value', (snapshot)=> {
const state = snapshot.val()
this.setState({reservas:state}) })
}
readUsersData();
}
This will do the job.