I'm using the SpaceX
API to build a personal project. I'm using React Router to dynamically load components, rather than refreshing the whole website.
Here is my LaunchDetails
component where I'm trying to output some data:
import React, { Component } from 'react'
class LaunchDetail extends Component {
state = {
launch: []
}
async componentDidMount () {
try {
const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
const data = await res.json()
this.setState({
launch: data,
rocket: data.rocket
})
} catch (e) {
console.log(e)
}
}
render () {
const { launch, rocket } = this.state
console.log(rocket)
return (
<div>
<div>
<h1>{launch.mission_name}</h1>
<p>SpaceX Flight Number: {launch.flight_number}</p>
<p>Launched: {launch.launch_year}</p>
<p>Rocket: {rocket.rocket_name}, {rocket.rocket_type}</p>
</div>
</div>
)
}
}
export default LaunchDetail
Data one level deep like launch.mission_name
is displaying correctly... However, when I try and go down another level, say, rocket.rocket_name (eg: launch.rocket.rocket_name)
, it throws the above error.
What is strange is that this works in another component, but that is using a different end point (all the data) and I'm mapping through it. Not sure if the way I'm calling the data in this component is to blame or not...
Does anyone have any idea why this could be happening?
EDIT: I've updated the code to be simpler after receiving some comments, error still persists:
import React, { Component } from 'react'
class LaunchDetail extends Component {
state = {
launch: []
}
async componentDidMount () {
try {
const res = await fetch(`https://api.spacexdata.com/v3/launches/${this.props.match.params.flight_number}`)
const data = await res.json()
this.setState({
launch: data
})
} catch (e) {
console.log(e)
}
}
render () {
const { launch } = this.state
return (
<div>
<div>
<h1>{launch.mission_name}</h1>
<p>SpaceX Flight Number: {launch.flight_number}</p>
<p>Launched: {launch.launch_year}</p>
<p>Rocket: {launch.rocket.rocket_name}, {launch.rocket_type}</p>
</div>
</div>
)
}
}
export default LaunchDetail