im trying to make api call with axios + node.js , im getting data in console however when i try to retrieve the nested values im getting error Cannot read property 'statistics' of undefined. in console when i hover over it i get data.data.[0].statistics.population_density.value But in my code it doesnt work. can someone explain what imi doing wrong ? thanks
[
data:
{
data: Array(1) {
0: {
{
"statistics": {
"population_density": {
"source_name": "NASA Socioeconomic Data and Applications Center (SEDAC) – Hosted by CIESIN at Columbia University",
"value": 13543,
"description": "The number of inhabitants per square kilometer around this point."
}
},
"location": {
"latitude": 37.769456,
"longitude": -122.429128
}
}
]
handleSelect = address => {
this.setState({
address,
});
console.log(this.state.address);
geocodeByAddress(address)
.then(res => getLatLng(res[0]))
.then(({
lat,
lng
}) => {
this.setState({
latitude: lat,
longitude: lng,
isGeocoding: false,
});
this.setState({
isLoaded: true
});
})
.catch(error => {
this.setState({
isGeocoding: false
});
console.log('error', error); // eslint-disable-line no-console
});
console.log(this.state.latitude);
console.log(this.state.longitude);
var param = {
lat: this.state.latitude,
long: this.state.longitude,
temp: 1,
};
axios
.post(`http://localhost:5000/search-data`, {
param,
})
.then(data => {
console.log(data);
this.setState({
value: data.data[0].statistics.population_density.value,
});
});
};
You need data.data.data[0]
:
.then(data => {
console.log(data);
this.setState({
value: data.data.data[0].statistics.population_density.value,
});
});
The output of console.log(data)
shows that this object - which is stored in a variable named data
- has a property that is called data
which in turn again has a property called data
.
I would suggest to rename the data
parameter to response
because that's what axios is actually giving you:
.then(response => {
console.log(response);
this.setState({
value: response.data.data[0].statistics.population_density.value
});
});
Then the error should be obvious. A response
does not consist only of data.
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.