Reputation: 323
I am currently using firebase realtime database to store information and am using component did mount to set the state. However, the states which are updated are initially set as null. Therefore, the first time the page loads, it renders exactly that - null, nothing.
I have tried passing props to the component through the main app.js component but it didnt work either. Are there any suggesstions on how to work my way around this?
The objective is to get the component to only render once the state has updated from null.
My code is below;
this.state = {
burnItClasses: null,
masterAbsClasses: null,
BodyToneClasses: null,
}
componentDidMount(){
let bodyToneClasses = [];
let btRef = firebase.database().ref("Bodytone");
btRef.on('value', (data)=>{
let bClassObjs = data.val();
let keys = Object.keys(bClassObjs);
keys.forEach((el)=>{
bodyToneClasses.push(bClassObjs[el])
})
this.setState({
BodyToneClasses: bodyToneClasses,
})
});
}
JSX:
<ul className="classtimesanddates">
{this.state.BodyToneClasses ? this.state.BodyToneClasses.map((element)=>{
return <li>{element.date} at {element.time}</li>
}) : "No scheduled classes available"}
</ul>
Thanks for the assistance!
Upvotes: 0
Views: 636
Reputation: 598740
Since it takes some time to load the data from Firebase's servers, it is normal that you'll initially render the UI without that data in it. That's why you can provide the initial state.
If you only want to render the list once data is available, you can put the condition around the ul
:
this.state.BodyToneClasses ? <ul className="classtimesanddates">
{this.state.BodyToneClasses.map((element)=>{
return <li>{element.date} at {element.time}</li>
})
</ul> : ""
Or, if you want to also display when the data has loaded and no classes are available:
this.state.BodyToneClasses ? <ul className="classtimesanddates">
{this.state.BodyToneClasses.length > 0 ? this.state.BodyToneClasses.map((element)=>{
return <li>{element.date} at {element.time}</li>
}) : "No classes available"
</ul> : ""
Upvotes: 1