Olawale Oladiran
Olawale Oladiran

Reputation: 631

How to redirect in react if prop is undefined

I'm passing props from another page into this page and it works fine. So I decided to copy the route of the receiving page into another tab, so it throws this error:

   TypeError: Cannot read property 'myData' of undefined

which is understandable because no props were passed. What I want to do is to route to another page since there's no prop defined with the below line of code:

   componentDidMount() {
        this.props.location.state.myData === undefined && this.props.history.push('/');

        this.fetchData(data);
   }

But it's not working, it's giving me the same error as above. What could I be doing wrong and how do I fix this?

Upvotes: 0

Views: 834

Answers (1)

kyle
kyle

Reputation: 2638

In your example, it isn't saying that myData is undefined, it's saying that it can't read the property myData of undefined. I.e the state property of location is undefined.

componentDidMount() {
  if (this.props.location.state === undefined) {
    this.props.history.push('/');
    return;
  }
  // else
}

Upvotes: 1

Related Questions