title: How can I conditionally redirect to a page after the axios response in react?
body: <p>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 <code>http://userapi.com/login</code> in loop. What I'm trying to achieve is, if the userinfo state is empty initially then redirect to the login page and authenticate.</p>
  <pre><code>class MyComponent extends React.Component {
    constructor() {
      super()
      this.state = {
        userinfo:{}
      }
    }
    
    componentDidMount(){
      axios.get('http://userapi.com/user')
      .then(res =&gt; {
          const userinfo = res.data;
          this.setState({ userinfo });
      })
      .catch(err =&gt; {
          console.log(&quot;Fetch error&quot;, err)
      })
      if (Object.keys(this.state.userinfo).length === 0) {
          window.location = 'http://userapi.com/login';
      }
    }
    render() {
      return (
        &lt;React.Fragment&gt;
          &lt;Header&gt;Welcome&lt;/Header&gt;
        &lt;/React.Fragment&gt;
      )
    }
  }
  </code></pre>
  <p>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)</p>