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
You need to do conditional check before accessing nested objects like
if(devicetype.data){
console.log(devicetype.data.device_elements);
console.log(devicetype.data.type_name);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.