I have Restaurants
component which is responsible for listing restaurants from Zomato Dev APIs. I have passed Category
and City
from other components to Restaurants
component.
I am opening Restaurants
component with below code :
this.props.history.push(
{
pathname : '/restaurants',
valueCategory : this.props.location.valueA, // CATEGORY
valueCity : this.state.cities[index] // CITY
});
I want to use these valueCategory
and valueCity
in calling /search
api.
Code :
class Restaurants extends React.Component {
constructor(props) {
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
this.getRestaurants = this.getRestaurants.bind(this);
}
componentDidMount() {
// I AM GETTING ERROR 'TypeError: Cannot read property 'name' of undefined' ON THIS LINE
console.log("Component Did Mount Restaurant : " + this.props.location.valueCity.name);
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log("Component Did Update :", prevProps);
//THIS PRINTS prevProps, WHICH CONTAINS valueCity and valueCategory but I am unable to access them
return false;
}
render() {
let category, city;
category = '';
city = '';
if(!isUndefined(this.props.location.valueCategory)) {
category = <p>You selected Category as : {this.props.location.valueCategory.categories.name}</p>;
}
if(!isUndefined(this.props.location.valueCity)) {
// STRANGLY, THIS LINE WORKS FINE! WHEN I AM ACCESSING valueCity.name
city = <p>You selected City as : {this.props.location.valueCity.name}</p>;
}
console.log(this.props.location);
return (
<div>
{category}
{city}
</div>
);
}
}
My question is :
- I am able to access
{this.props.location.valueCity.name}
inrender()
method - But I am not able to access the same in
componentDidMount()
or any other method? I am getting crash
TypeError: Cannot read property 'name' of undefined
Have you tried componentDidUpdate life cycle method? compare the props incoming to this method
**check and let me know