MattBlack
MattBlack

Reputation: 3828

React router redirect

I have a function 'getData' which is called when the component mounts. If there is an error thrown from axios I wish to send the user to the login page. The code below gives me the following error:

Unhandled Rejection (TypeError): Cannot read property 'props' of undefined

on the uncommented line:

this.props.history.push('/login');

Interestingly though if I move that line outside of the axios function then I redirect without an issue (where the commented this.props.history.push('/login') is).

How do I take the user to the login page when an axios error is thrown?

getData(currentComponent) {

  //this.props.history.push('/login');

    axios.get('******.php', {

    })
    .then(function (response) {
      console.log(response.data[0]);
      currentComponent.setState({tableData: response.data});
    })
    .catch(function (error) {
     this.props.history.push('/login');
      console.log(error);
    });
}

Upvotes: 1

Views: 64

Answers (2)

Hurobaki
Hurobaki

Reputation: 4068

Or you can use ES6 syntax with arrow function to keep global this inside your function.

const getData = async (currentComponent) => {
      //this.props.history.push('/login');
    try {
      const response = await axios.get('******.php', {})

      console.log(response.data[0]);
      currentComponent.setState({tableData: response.data});
    } catch (e) {
      this.props.history.push('/login');
      console.log(e);
    }
}

Upvotes: 0

Thomas Kekeisen
Thomas Kekeisen

Reputation: 4406

You have to save the reference to this since it will change inside the callback of axios.get:

getData(currentComponent) {
    const self = this;
  //this.props.history.push('/login');

    axios.get('******.php', {

    })
    .then(function (response) {
      console.log(response.data[0]);
      currentComponent.setState({tableData: response.data});
    })
    .catch(function (error) {
     self.props.history.push('/login');
      console.log(error);
    });
}

Another option may be to use an arrow function for the definition of getData.

Upvotes: 2

Related Questions