I am using axios to fetch data from api. My router is:
<Route exact path='/device/:id/update' render={(props) => <DeviceTypeUpdate {...props} />} />
My componentDidMount is :
componentDidMount() {
console.log('------this.props.match.id----', this.props.match.params.id)
const ied = this.props.match.params.id
axios({
url: 'http://127.0.0.1:8000/api/devicetypeget/'+ied,
method: 'get',
headers: {
'Content-Type' : 'application/json'
}
})
.then(function(response) {
return response;
})
.then(function (devicetype) {
this.setState(function () {
return {devicetype: devicetype, isLoaded: true}
})
}.bind(this))
.catch(function (error) {
this.setState(function () {
return {error, isLoaded: true}
})
}.bind(this))
}
In my render method, I tried to log data in console, as given below:
const {error, isLoaded, devicetype} = this.state
console.log('----error----', error);
console.log('----devicetype in render----', devicetype.data);
devicetype.data prints out the JSON object which has nested data in it as given below:
assignment_date: {$date: 1548744545634}
device_elements: {type: "switch", name: "board", state: "some state"}
dev_stage: "PLANNING"
type_description: "some description"
type_name: "Board"
_id: 1
when I console.log(devicetype.data.device_elements) or any other attribute
It throws an error "TypeError: Cannot read property 'type_name' of undefined"
What am I doing wrong. Please help me
this.state.devicetype? My guess is that your component is rendering beforethis.state.devicetype.datais set in response to the axios call, so the initial render is trying to access an object that does not exist (yet).render()function to handle the case where data is not yet loaded. In pseudocode:if (dataIsNotLoaded) displayLoadingMessage else displayData