Error: Invalid hook call, React router history

Hi guys, I’m a react beginner and I tried to execute a function to logout, but I get this error. I think the error is related to the useHistory function because if I remove it, everything works perfectly.
Or in any case, someone knows how to redirect to another page programmatically

Error: Invalid hook call. Hooks can only be called inside of the body of a function component

This is my code.

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import token from '../services/token'
import api from '../services/api'
import { useHistory } from 'react-router-dom';

const noLogueado = <React.Fragment>
    <li className="nav-item">
        <Link className="nav-link" to="/login">Login</Link>
    </li>
    <li className="nav-item">
        <Link className="nav-link" to="/register">Registrarse</Link>
    </li>
</React.Fragment>;

const logueado = <li className="nav-item dropdown">
    <a className="nav-link dropdown-toggle" href="#" role="button" id="dropdownPerfil" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        NAME USUARIO
    </a>

    <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownPerfil">
        <a className="dropdown-item" href="#">Mi Perfil</a>
        <a className="dropdown-item" href="#" onClick={() => Logout()}>Cerrar sesión</a>
    </div>
</li>;

const Logout = () => {
    let history = useHistory();

    api.post("logout", "").then(
        (data) => {
            // token.remove();
            history.push('/login');
        },
        (error) => {
            // token.remove();
            history.push('/login');
        }
    );
}

export class NavBar extends Component {
    
    render() {
        return (
            <nav className="navbar navbar-expand navbar-dark bg-dark">
                <Link className="navbar-brand" to="/">
                    Home</Link>
                <div className="collapse navbar-collapse">
                    <ul className="navbar-nav ml-auto">
                        {
                            token.isValid() ? logueado : noLogueado
                        }
                    </ul>
                </div>
            </nav>
        )
    }
}

export default NavBar

1 thought on “Error: Invalid hook call, React router history”

  1. Rename Logout to useLogout (because it’s a custom hook):

    const useLogout = () => {
      let history = useHistory();
    
      return useCallback(() => api.post("logout", "").then(
        (data) => {
          // token.remove();
          history.push('/login');
        },
        (error) => {
          // token.remove();
          history.push('/login');
        }
      ), [history]);
    }
    

    Convert logueado to a function component (Logueado), and get the logout function from useLogout. Call the function in onClick.

    const Logueado = () => {
      cosnt logout = useLogout()
    
      return (
        <li className="nav-item dropdown">
            <a className="nav-link dropdown-toggle" href="#" role="button" id="dropdownPerfil" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                NAME USUARIO
            </a>
    
            <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownPerfil">
                <a className="dropdown-item" href="#">Mi Perfil</a>
                <a className="dropdown-item" href="#" onClick={logout}>Cerrar sesión</a>
            </div>
        </li>;
      )
    }
    
    Reply

Leave a Comment