'React Nested Object Gives Error
I have a component that works and will return data from State as long as it isn't nested. However, if I need to dig a little deeper within the object, I get an error: "TypeError: Cannot read property 'name' of undefined".
I'm positive that there is a value for it (checked Inspector and the variable does indeed have a value, that's how I knew what to put in code). Why does it work for a higher value, but not the lower value?
class Concert extends Component {
constructor(props) {
super(props);
this.state = ({
concert:''
})
}
componentDidMount(){
var concertid = `${REQ_URL}/${this.props.match.params.concertid}`;
fetch(concertid, {
method: 'GET'
})
.then(response => response.json())
.then(json => {
this.setState({
concert:json
})
})
}
render() {
return (
<div>
<Header />
<div className="concert">
<div className="venue">
//THIS IS THE PART THAT RETURNS ERROR
//this.state.concert.id returns a correct value
//POSITIVE this.state.concert.artist.name DOES CONTAIN VALUE
Venue: {this.state.concert.artist.name}
</div>
</div>
</div>
)
}
}
Solution 1:[1]
easy, api calls are asynchronous so this.state.concert.artist.name will be {"empty"} until you get the api response.
use this:
Venue: {this.state.concert && this.state.concert.artist && this.state.concert.artist.name}
Solution 2:[2]
The problem is it's trying to render before the data is there since the API call is asynchronous.
A nicer way to fix this is to extract the values using es6 object destructuring with defaults:
const {
id,
artist: {
name
} = {}
} = this.state.concert;
-
Venue: {name}
This way, if artist is not present you'll just get undefined instead of throwing an error
Also concert should be an object by default in the constructor:
this.state = {
concert: {}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Austin Greco |
