Sooraj
Sooraj

Reputation: 10567

React router `this.props.history.push` - history not defined

I have this logout function:

logOut = () => {
    axios
      .delete(`${apiUrl}/logout`)
      .then(response => {
        if (response.status === 204) {
          localStorage.removeItem('key', response.headers.authorization)
          localStorage.removeItem('id', response.data.id)
          // return <Redirect to="/login" />
          this.props.history.push(`/login`)
        }
      })
      .catch(error => {
        console.log(error)
      })
  }

this.props.history.push('/something') works on every other occasion. But here it says cannot read push of undefined. I tried return <Redirect to="/login" /> which doesn't work too.

What am I doing wrong?

Upvotes: 1

Views: 8224

Answers (1)

Pouya Jabbarisani
Pouya Jabbarisani

Reputation: 1121

It may because of one of these reasons:

1- You need to pass your component to withRouter when you are using history.push:

    import { withRouter } from 'react-router-dom

   // ... codes of component in here ...

    export default withRouter(componentName) // at the end of component

2- this is referring to axios and you need to define this over the axios with another name and use it in axios e.g.:

var that = this;

 // then use that in axios

Upvotes: 15

Related Questions