title: In react, what is the best way to perform an API call and redirect before Render()?
body: <p>I mostly do backend, so my javascript isn't all that, but I'm having a problem in my admin panel I'm designing. Some parts of the site can only be accessed by certain users. </p>
  
  <p>Each time the protected component should load, I send a request to my REST server, which returns back either 200 or a 403, the 200 response contains a key called <code>redirect</code>, which is <code>False</code>. So my thinking was to do the following:</p>
  
  <pre><code>...
  import { Redirect } from 'react-router-dom';
  import axios from 'axios';
  
  
  class MyProtectedComponent extends Component {
      constructor(props) {
          super(props);
  
          this.state = {
              authCalled: false,
              redirect: true,
          };
      }
  
      componentDidMount() {
          console.log("mounting...")
          axios.get('&lt;https://url&gt;',
          {headers: {"Authorization": localStorage.getItem("token")}})
          .then(res =&gt; {
              this.setState({
                  redirect: res.data.data.redirect,
                  authCalled: true,
              });
          })
      }
  
      render() {
          if (this.state.authCalled === false) {
             return (
                 &lt;div className="animated fadeIn"&gt;
                 &lt;Row&gt;
                 &lt;Col&gt;
                 authenticating...
                 &lt;/Col&gt;
                 &lt;/Row&gt;
                 &lt;/div&gt;
             )
         }
  
         if (this.state.redirect === true) {
             return &lt;Redirect to={{pathname: "/nonauthpage"}} /&gt;;
         }
  
     return ( ....... &lt;main code&gt; ..... )
  </code></pre>
  
  <p>Now if the server sends back the 200 for the user is allowed to access, the component loads, but if not, the page gets stuck in the <code>&lt;authenticating&gt;</code> phase and never <code>Redirect</code>s. </p>
  
  <p>All of my javascript is self-taught, If what I'm doing is bad practice for performing this type of thing, please let me know how to properly do it, or show me why this is not working so I get it working.</p>