title: Need to Execute Function before render() in ReactJS
body: <p>I've created a login system with React which stores a session when the user logs in. When the page is reloaded, I have added a function which should check if the session exists and then either <code>setState()</code> to <code>true</code> or to <code>false</code>.</p>
  
  <p>As I'm new to React, I'm not sure how to execute this function. Please see my code below for <strong>App.js</strong>:</p>
  
  <pre><code>import React from 'react';
  import './css/App.css';
  import LoginForm from "./LoginForm";
  import Dashboard from "./Dashboard";
  
  class App extends React.Component {
  
      constructor(props) {
          super(props)
          this.state = {
              renderLoginForm: true
          };
          this.handleLoginFormMount = this.handleLoginFormMount.bind(this);
      }
  
      handleLoginFormMount() {
          this.setState({
              renderLoginForm: false
          });
      }
  
      // Check session function.
      checkSession() {
          fetch('/check-session', {
              credentials: 'include'
          })
          .then((response) =&gt; {
              return response.json();
          })
          .then((sessionResult) =&gt; {
              if (sessionResult.username) {
                  console.log('false');
                  this.setState({
                      renderLoginForm: false
                  });
              } else {
                  console.log('true');
                  this.setState({
                      renderLoginForm: true
                  });
              }
          })
          .catch((error) =&gt; {
              console.log('Error: ', error);
          });
      }
  
      render() {
  
          checkSession();
  
          return (
              &lt;div className="App"&gt;
                  {this.state.renderLoginForm ? &lt;LoginForm mountLoginForm={this.handleLoginFormMount} /&gt; : null}
                  {this.state.renderLoginForm ? null : &lt;Dashboard /&gt;}
              &lt;/div&gt;
          );
      }
  }
  
  export default App;
  </code></pre>
  
  <p>Having <code>checkSession()</code> in this position outputs the following in the console when loading the page:</p>
  
  <p><code>Line 50:  'checkSession' is not defined  no-undef</code></p>
  
  <p>If I put the function outside of the <code>class App extends React.Component {}</code>, then it tells me that I cannot set the state of undefined.</p>