title: Strategies to implementing a conditional Navbar if a user is logged in or not
body: <p><strong>Background</strong>: I am creating a very basic application with 4 different capabilities: Signup, Login, Searching, and Creating content. As of right now, I can log in to users and prevent unauthorized users from going to protected routes. This is shown below in my <code>Protected.js</code> component. However, I am struggling to figure out a way to also <strong>conditionally display a login/logout button in my navigation bar located in my <code>App.js</code></strong>.</p>
  <p><strong>Followup Questions</strong>: Should I move the authentication logic out of my <code>Login.js</code> route and into my main <code>App.js</code> component and pass the state down? Wouldn't that be very inefficient, because every time I am rendering a new view, the <code>App.js</code> is performing another fetch with my backend API to verify if the user has a non-expired session? This might appear trivial to some, but I am having a difficult time wrapping my head around how to conditionally show a login/logout button efficiently.  I have looked into Context API, so I would be open to some advice down that route if you feel necessary, but I am not familiar with Redux(<em>I just began to React a week ago</em>). I am looking for well-thought-out strategies, so I would greatly appreciate it if you could do your best to provide complete and coherent responses. I really appreciate it.</p>
  <p><strong>App.js</strong></p>
  <pre><code>class App extends Component {
      render() {
          return(
              &lt;Router&gt;
                  &lt;div&gt;
                      &lt;Navbar bg=&quot;light&quot; variant=&quot;light&quot;&gt;
                          &lt;Navbar.Brand href=&quot;#home&quot;&gt;My Application&lt;/Navbar.Brand&gt;
                          &lt;Nav className=&quot;mr-auto&quot;&gt;
                              &lt;Link to=&quot;/signup&quot; className=&quot;nav-link&quot;&gt;Signup&lt;/Link&gt;
                              &lt;Link to=&quot;/login&quot; className=&quot;nav-link&quot;&gt;Login&lt;/Link&gt;
                              &lt;Link to=&quot;/feed&quot; className=&quot;nav-link&quot;&gt;Search&lt;/Link&gt;
                              &lt;Link to=&quot;/create-post&quot; className=&quot;nav-link&quot;&gt;Create&lt;/Link&gt;
                          &lt;/Nav&gt;
                          &lt;Form inline&gt;
                              &lt;Button variant=&quot;outline-primary&quot;&gt;Logout&lt;/Button&gt;
                          &lt;/Form&gt;
                      &lt;/Navbar&gt;
                  &lt;/div&gt;
                  &lt;Switch&gt;
                      &lt;Route path = '/signup' component = {Signup} /&gt;
                      &lt;Route path = '/login' component = {Login} /&gt;
                      &lt;Route path = '/feed' component = {Feed} /&gt;
                      &lt;ProtectedRoute path = '/create-post' component = {CreatePost} /&gt;
                  &lt;/Switch&gt;
  
              &lt;/Router&gt;
          )
      }
  }
  </code></pre>
  <p><strong>Login.js</strong></p>
  <pre><code> class Login extends Component {
      constructor(props) {
          super(props)
  
          this.state = {
              username: &quot;&quot;,
              password: &quot;&quot;
          }
  
          this.handleChange = this.handleChange.bind(this)
          this.handleSubmitForm = this.handleSubmitForm.bind(this)
      }
  
      handleChange(event) {
          //console.log(event.target.name)
          this.setState({[event.target.name]: event.target.value})
      }
  
      handleSubmitForm() {
          const user = {
              username: this.state.username,
              password: this.state.password
          }
  
          const url = 'http://localhost:9000/api/login'
  
          fetch(url, {
              method: 'POST',
              credentials: 'include',
              headers: {
                  'Content-Type': 'application/json'
              },
              body: JSON.stringify(user)
          })
          .then((response) =&gt; response.json())
          .then((data) =&gt; {
              if (data.status === 1) {
                  this.props.history.push('/feed')
              }
              console.log(data)
          })
          .catch((error) =&gt; {
              console.log('Error', error)
          })
      }
  
      render() {
          return (
          &lt;div&gt;
              &lt;Card className=&quot;card-login&quot; style={{ width: '18rem' }}&gt;
                  &lt;Card.Body&gt;
                  &lt;Card.Title&gt;Login&lt;/Card.Title&gt;
                      &lt;Form&gt;
                          &lt;Form.Group&gt;
                              &lt;Form.Control placeholder =&quot;Username&quot;
                                            name = &quot;username&quot;
                                            value = {this.state.username}
                                            onChange = {this.handleChange}/&gt;
                          &lt;/Form.Group&gt;
                          &lt;Form.Group&gt;
                              &lt;Form.Control type =&quot;password&quot;
                                            placeholder=&quot;Password&quot;
                                            name = &quot;password&quot;
                                            value = {this.state.password}
                                            onChange = {this.handleChange} /&gt;
                          &lt;/Form.Group&gt;                   
                      &lt;Button variant =&quot;primary&quot;
                              value=&quot;Submit&quot;
                              onClick={this.handleSubmitForm}&gt;Submit
                      &lt;/Button&gt;
                      &lt;/Form&gt;
                  &lt;/Card.Body&gt;
              &lt;/Card&gt;         
          &lt;/div&gt;)
      }
  }
  </code></pre>
  <p><strong>Protectedroute.js</strong></p>
  <pre><code>class ProtectedRoute extends Component {
      constructor(props) {
          super(props)
  
          this.state = {
              isAuthenticated: false,
              isLoading: true
          }
          this.isAuthenticated = this.isAuthenticated.bind(this)
      }
  
      componentDidMount() {
          this.isAuthenticated()
      }
  
      isAuthenticated() {
          const url = 'http://localhost:9000/api/auth'
          fetch(url, {
              method: 'GET',
              credentials: 'include',
              headers: {
                  'Content-Type' : 'application/json'
              }
          })
          .then((response) =&gt; response.text())
          .then((data) =&gt; {
              if (data === 'true') {
                  this.setState({
                      isAuthenticated: true,
                      isLoading: false
                  })
              } else {
                  this.setState({
                      isAuthenticated: false,
                      isLoading: false
                  })
              }
          })
          .catch((err) =&gt; {
              console.log('Error', err)
          })
      }
      render() {
          const Component = this.props.component
          if (this.state.isLoading === true) {
              return (&lt;div&gt;Loading&lt;/div&gt;)
          }
          return(
              &lt;Route render={(props) =&gt; this.state.isAuthenticated &amp;&amp; !this.state.isLoading ? (&lt;Component {...this.props}/&gt;) : (&lt;Redirect to ='/login' /&gt;)} /&gt;
          )
              
      }
  }
  </code></pre>
  <p><strong>api.js (Express Backend)</strong></p>
  <pre><code>router.post('/login', function(req,res,next) {
      const query1 = &quot;SELECT * FROM users WHERE username = TRIM(?) AND pass = TRIM(?)&quot;
      database.query(query1, [req.body.username, req.body.password])
      .then((result) =&gt; {
          if (result.length) {
              if (req.session.username) {
                  res.json({'message': 'You are already logged in', 'status': 0})
              } else {
                  req.session.username = req.body.username
                  res.json({'message': 'You have successfully logged in', 'status': 1})
              }
          } else {
              if (req.session.username) {
                  res.json({'message': 'You are already logged in', 'status': 0})
              } else {
                  res.json({'message': 'Incorrect Credentials', 'status': 0})
              }
          }
      }).catch((err) =&gt; res.send(err))
  })
  
  
  
  router.get('/auth', (req, res, next) =&gt; {
      if (req.session.username) {
          res.send(true)
      } else {
          res.send(false)
      }
  })
  </code></pre>