Reputation: 49
Im using firebase.auth().onAuthStateChanged in order to change my state, if the user is not null, I want to update my state and set the user info in it, however when I try to do so, I get an infinite loop, however when I delete the this.setState({userInfo: user}) the code works without problems, below my code:
class Test extends React.Component {
state = {
toDashboard: true,
userInfo: null
}
render() {
firebase.auth().onAuthStateChanged(user =>{
if(!user){
this.setState({toDashboard: false});
}else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
this.setState({userInfo: user});
}
})
if (this.state.toDashboard === false) {
return <Redirect to='/auth/login' />
}
return (
<>
<Sidebar
{...this.props}
routes={routes}
logo={{
innerLink: "/admin/index",
imgSrc: require("assets/img/brand/LogoMorado.png"),
imgAlt: "Logo"
}}
/>
<div className="main-content" ref="mainContent">
<AdminNavbar
{...this.props}
brandText={this.getBrandText(this.props.location.pathname)}
/>
<Switch>{this.getRoutes(routes)}</Switch>
<Container fluid>
<AdminFooter />
</Container>
</div>
</>
);
}
}
export default Test;
Upvotes: 0
Views: 639
Reputation: 10254
Don't use setState({})
in render()
.
It causes the infinite loop
.
basically, componentDidMount()
do that instead of render()
.
and you should learn about React Life Cycle.
https://reactjs.org/docs/react-component.html
componentDidMount(){
firebase.auth().onAuthStateChanged(user =>{
if(!user){
this.setState({toDashboard: false});
}else{ //HERE is where I get the inifinite loop, if I delete the ELSE, it does not go into an infinite loop
this.setState({userInfo: user});
}
})
}
render() {
return (
<>
{ (this.state.toDashboard === false)? <Redirect to='/auth/login' /> : null }
<Sidebar
{...this.props}
routes={routes}
logo={{
innerLink: "/admin/index",
imgSrc: require("assets/img/brand/LogoMorado.png"),
imgAlt: "Logo"
}}
/>
<div className="main-content" ref="mainContent">
<AdminNavbar
{...this.props}
brandText={this.getBrandText(this.props.location.pathname)}
/>
<Switch>{this.getRoutes(routes)}</Switch>
<Container fluid>
<AdminFooter />
</Container>
</div>
</>
);
}
Upvotes: 3