Reputation: 657
I want to pass my User uid to my child component but the problem is that the method onAuthStateChanged needs more time to recive than the render function. And after setState is called the render function will not rerender.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../index.css';
import SP_Quiz from'./SP_Quiz';
import Register from './Register';
import Login from './Login';
import Header from './Header';
import Category from './Category';
import Profile from './Profile';
import {fire} from './Firebase';
var ReactRouter = require('react-router-dom');
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Switch = ReactRouter.Switch;
var url = window.location.href.toString().split(window.location.host)[1];
var category = url.substr(6);
var userLang = navigator.language || navigator.userLanguage;
if ((userLang != 'de') && (userLang != 'jp')) {
userLang = 'en'
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
userUid : null
}
fire.auth().onAuthStateChanged( (user) => {
if (user) {
this.setState({
userUid: user.uid
})
})
}
render(){
return(
<Router>
<div>
<Header />
<Switch>
<Route path='/quiz' render={()=><SP_Quiz category={category} language={userLang}
user={this.state.userUid} playerProgress="0"/>} />
<Route path='/register' component={Register} />
<Route path='/login' component={Login} />
<Route path='/category' render={()=><Category language="de"/>} />
<Route path='/profile' component={Profile} />
</Switch>
</div>
</Router>
);
}
}
export default App;
I also try to make an force rerende after the onAuthStateChaned is done with this.forceUpdate() but it also don't work.
Upvotes: 0
Views: 660
Reputation: 2690
Try to put your method onAuthStateChanged
not in the constructor but in a life cycle method like componentDidMount
and make it async/await.
I'm guessing this method make an HTTP call so there is some network delay between your component being rendered and the request. So I'm guessing your method is returning a Promise.
class App extends Component {
// ES6 make writting a class simpler - don't need
// explicitly write constructor. Just a state Object
state = {
userid: null
}
componentDidMount = async () => { // need an arrow function to bind(this)
try {
const user = await fire.auth().onAuthStateChanged()
if (user) {
this.setState({
userUid: user.uid
})
} catch (e) {
console.log(e)
}
}
// rest of your class
}
SIDE NOTE :
You are mixing import XXX from 'XXX'
with var YYY = require('YYY')
. Frontend should use the first one.
And it's not mandatory but use const
everywhere except when you need to reassign where you gonna use let
. Forget var
Upvotes: 1