0
votes

I'm trying to conditionally return a navbar if an user is logged in. Users token is saved into localStorage and then sent into the backend system. If the backend returns an error message, it means that the user is not logged in, thus the code shouldn't render a navbar. However, it isn't quite working the way I'm expecting it to work and I'm really in need of someone else's knowledge at this point.

The error message I'm getting is:

"Nav(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."

Nav.js

import React from 'react';
import {Link} from 'react-router-dom';
import {tokenCheck} from '../utils/MediaAPI';

const Nav = () => {
  tokenCheck(localStorage.getItem('Login-token')).then(data => {
    if (data.message) {
      return null;
    } else {
      return (
          <nav>
            <ul>
              <li>
                <Link to="/home">Home</Link>
              </li>
              <li>
                <Link to="/profile">Profile</Link>
              </li>
              <li>
                <Link to="/logout">Logout</Link>
              </li>
            </ul>
          </nav>
      );
    }
  });
};

export default Nav;

Render from my App.js parent component.

  render() {
    return (
        <Router>
          <Nav/>
          <Route exact path="/" render={(props) => (
              <Login {...props} setUser={this.setUser}/>
          )}/>
          <Route exact path="/home" render={(props) => (
              <Home {...props} picArray={this.state.picArray}/>
          )}/>
          <Route exact path="/profile" render={(props) => (
              <Profile {...props} userData={this.state.user}/>
          )}/>
          <Route exact path="/single/:id" component={Single}/>
        </Router>
    );
  }

Any help will be greatly appreciated!

1
You are returning in a promise. you'll have to await the resultDTul
@DTul There's no return in Nav, so it returns undefined, not a promise. Regardless, don't forget that async/await functions also return promises.Jordan Running

1 Answers

3
votes

You want to not even deal with <Nav /> if you don't want to render anything at all. In its parent, use

tokenCheck(localStorage.getItem('Login-token')).then(data => {
    this.setState({errorMessage: data.message})
}

Or whatever you want to call it in your state. Place that somewhere like componentDidMount and in render use

{!this.state.errorMessage && </Nav />}

That way, if there is an error message, the component you don't want to render will never even pop up.