Winda
Winda

Reputation: 11

ReactJS TypeError: Cannot read property 'push' of undefined

I build my Apps and learn ReactJS

My code error until now, i try to search on internet and forums but can't fix. Here my code :

logout(){
    localStorage.removeItem("token");
    localStorage.clear();
    if(localStorage.getItem('token') === null){
        this.props.history.push('/login')
    }
}

Error : TypeError: Cannot read property 'push' of undefined

Please Help Me

Upvotes: 1

Views: 8538

Answers (4)

Shrawan
Shrawan

Reputation: 7246

I have faced similar issue while creating custom portal to show model like logout/login.

const App = () => {
  const [modal] = useSelector(({ modal }) => [modal])
  return (
    <>
      <Portal modal={modal} />  
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </>
  );
}

export default App;

Correct way- Portal must me child of BrowserRouter.

const App = () => {
      const [modal] = useSelector(({ modal }) => [modal])
      return (
        <>
          <BrowserRouter>
            <Portal modal={modal} />  
            <Routes />
          </BrowserRouter>
        </>
      );
   }

For more reference see Router.

Upvotes: 1

Prithwee Das
Prithwee Das

Reputation: 5226

My guess is your logout is within a component which is not a Route it self. By that what I mean is you're not doing <Route path="/" component={ComponentThatHasLogoutMethod} />

Only the components that are used as Route has history prop. if you need those in some other nested Component you can use the withRouter Higher order component from react-router-dom

export default withRouter(ComponentThatHasLogoutMethod)

This will pass the history prop to your component and you'll not get null.

Upvotes: 4

Psartek
Psartek

Reputation: 485

Solution Example with react hooks:

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    localStorage.removeItem("token")
    localStorage.clear()
    if(!localStorage.getItem('token')){
      history.push("/login")
    }
  }

  return (
    <button type="button" onClick={handleClick}>
      Login
    </button>
  );
}

More info you can find in docs https://reacttraining.com/react-router/web/api/Hooks/usehistory

Upvotes: 2

Abhisar Tripathi
Abhisar Tripathi

Reputation: 1659

We have two solutions for this problem -:

  • Replace function declaration with fat arrow notation declaration i.e -:
  logout = () => {
        localStorage.removeItem("token");
        localStorage.clear();
        if(localStorage.getItem('token') === null){
            this.props.history.push('/login');
        }
    }
  • We can bind logout function in the constructor -:
  constructor(props){
      super(props);
      this.logout = this.logout.bind(this);
  }

Upvotes: 0

Related Questions