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

4
  • 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 Commented Jan 2, 2020 at 8:09
  • can you please share more of your code? like the whole component Commented Jan 2, 2020 at 8:11
  • 1
    did you wrap your component in a withRouter HOC. example from docs Commented Jan 2, 2020 at 8:14
  • Hi, props.history doesn't have a value in it. It's type is undefined right now. This link may help a little net-informations.com/js/iq/unerror.htm Commented Jan 2, 2020 at 8:16

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.