How can I conditionally redirect to a page if the axios api is empty or a state is empty initially. In the following code I'm updating the state using axios and the user information is available in the state but the code keeps on calling to the http://userapi.com/login
in loop. What I'm trying to achieve is, if the userinfo state is empty initially then redirect to the login page and authenticate.
class MyComponent extends React.Component {
constructor() {
super()
this.state = {
userinfo:{}
}
}
componentDidMount(){
axios.get('http://userapi.com/user')
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
})
.catch(err => {
console.log("Fetch error", err)
})
if (Object.keys(this.state.userinfo).length === 0) {
window.location = 'http://userapi.com/login';
}
}
render() {
return (
<React.Fragment>
<Header>Welcome</Header>
</React.Fragment>
)
}
}
I'm able to redirect fine but issue is with continuous loop. Even though the user information is storing the redirection is called (happens in loop)