1

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

Winda
  • 11
  • 1
  • 2
  • your error message says Cannot read property 'push' of undefined, it means this.props.history is not exist, for debugging first console this.props.history – Vicky Kumar Jan 02 '20 at 08:09
  • can you please share more of your code? like the whole component – Siddharth Pal Jan 02 '20 at 08:11
  • 1
    did you wrap your component in a `withRouter` HOC. [example from docs](https://reacttraining.com/react-router/web/api/withRouter) – hotpink Jan 02 '20 at 08:14
  • Hi, props.history doesn't have a value in it. It's type is undefined right now. This link may help a little http://net-informations.com/js/iq/unerror.htm – Salvatore Allegra Jan 02 '20 at 08:16

4 Answers4

4

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.

Prithwee Das
  • 4,628
  • 2
  • 16
  • 28
2

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

Psartek
  • 481
  • 3
  • 9
1

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.

Community
  • 1
  • 1
Shrawan
  • 7,128
  • 4
  • 29
  • 40
0

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);
  }
Abhisar Tripathi
  • 1,569
  • 10
  • 21