I understand that setState()
is async by design in react, and I get why - because JS is single-threaded and so are browsers, therefore re-rendering is an expensive operation. I have a very (what seems to be) simple problem.
I am receiving some data from Firebase and I am setting that data to component state using setState()
, so i can ship it off as props to the About.js
component. What is happening is that the engine is skipping past the setState()
(naturally) because of it's async nature and injecting the props into the About.js
component. The props inside the About.js
component are null, because it is receiving the initial props from the parent component which is set initially to null.
I tried the whole callback approach, but i am stuck on this little quirk (I hope they add an operation down the road to choose between sync and async for setState()
).
Anyways, here's the code--- pretty simple. Thanks in advance for any help!
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
home_skills: null
}
this.sendSkillProps = this.sendSkillProps.bind(this);
}
sendSkillProps(delta) {
return (previousState, currentProps) => {
return {...previousState, home_skills: delta}
}
}
componentDidMount() {
// GET LIST HOME SKILLSET FROM FIREBASE
const db = firebase.firestore();
var skillset_ref = db.collection('SOME_COLLEC_ID').doc('SOME_DOC_ID');
skillset_ref.onSnapshot((doc) => {
if (doc.exists) {
this.setState(this.sendSkillProps(doc.data()));
}
else {
console.log("No such document!");
}
});
}
render() {
return (
<div className="App">
<Navbar />
<MainSplash />
<About madskills={this.state.home_skills} />
</div>
);
}} export default App;
About.js
export default class About extends React.Component {
constructor (props) {
super(props);
this.state = {}
}
componentDidMount() {
console.log(this.props.madskills); // LOGS AS NULL
}
render() {
return (
...
Thanks to @hussain.codes, this worked (thanks everyone else too!):
render() {
return (
<div className="App">
<Navbar />
<MainSplash />
{
this.state.home_skills != null ? <About madskills={this.state.home_skills} /> : <h1>Loading...</h1>
}
</div>
);
}