I am playing around with AppBase.io as a database and I don\'t understand why this component renders twice after getting an item? It seems as if the AppBase \"database\" ret
That's because appbaseRef.get
is asynchronous. ItemFull
does its initial rendering and you see first console.log
this.state.item._id
at the first time actually checks for _id
in a String Object ("") which is of course undefined.
Then this.setState
is called in componentWillMount
(which has already been mounted and rendered at least once) and updates the state forcing component to rerender because of state change.
This is why you see 2 console logs.
You cant prevent render()
hook from executing but you can make sure that you render your content only when the data has arrived:
render() {
console.log(this.state.item._id, '<-- console_log');
if(this.state.item) { // this will check if item is different than ''
return (
)
}
}
one more thing. Use componentDidMount for initial data fetching as it's the recommended place.