Altair312
Altair312

Reputation: 348

React Routing - Navbar doesn't update, updates with page refresh

I'm using just vanilla React with React-Router.

My current problem is that I am trying to detect whether the user on the page has a token or not, indicating whether he is logged in.

While writing routes for the Login/Register/Logout, I tried specifying that they should show based on whether you are logged in or not (if you are, show only logout, else show both register/login).

The problem is, my links do not get updated in my Navbar dynamically, but when refreshing the browser either with F5 or CTRL+F5, it works okay then. Can you help me out? I tried looking for other solutions here on StackOverflow, but none of them worked for me (using componentDidUpdate and so on)

import React from "react";
import { Route, Link, Switch, Redirect } from "react-router-dom";

import Cookies from "universal-cookie";

const cookies = new Cookies();

function handleClick(e) {
  cookies.remove("token");
}

class LoginButton extends React.Component {
  render() {
    return (
      <ul>
        <Link to="/login" onClick={handleClick}>
          Login
        </Link>
        <br />
        <Link to="/register">Register</Link>
      </ul>
    );
  }
}

class LogoutButton extends React.Component {
  render() {
    return (
      <ul>
        <Link to="/login" onClick={handleClick}>
          Logout
        </Link>
      </ul>
    );
  }
}

class NavBar extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillReceiveProps() {
    this.render();
  }

  render() {
    let token = cookies.get("token");
    let logButton;

    if (token === undefined) {
      logButton = <LoginButton />;
    } else {
      logButton = (
        <li>
          <LogoutButton />
        </li>
      );
    }
    return (
      <div>
        <ul>{logButton}</ul>
      </div>
    );
  }
}

export default NavBar;

Upvotes: 2

Views: 4182

Answers (1)

peter
peter

Reputation: 662

A component will only re-render (refresh without a browser refresh) if a state or prop has been updated. Currently, you seem to have neither. You will most likely need this cookies from outside your navbar as well (any other parts in your app where you want to test whether the user is logged in) - so I would move it to a parent component, then when invoking the Navbar, instantiate it such as:

<Navbar cookie={ userCookie: theUserCookie } />

Ideally, things like user cookies IMO are better stored in a redux state - then when another component updates the cookie, your navbar which references the redux store, will update as well.

Upvotes: 2

Related Questions