Utilizing the fetch-jsonp library, I attempted to retrieve data from the darksky API. However, upon fetching the data, I encountered a TypeError when trying to store it.
constructor(props) {
super(props);
this.state = {
daily: [],
hourly: [],
hourlySum: '',
dailySum: '',
loading: true,
error: null
};
}
componentDidMount() {
if (navigator.geolocation){
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var results = fetchJsonp(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`)
.then(result => {
this.setState({
daily: result.daily.data,
hourly: result.hourly.data,
hourlySum: result.hourly,
dailySum: result.daily,
loading: false,
error: null
});
})/*.catch(err => {
// Something went wrong. Save the error in state and re-render.
this.setState({
loading: false,
error: err
});
});*/
};
function error() {
console.log( 'geolocation error' )
};
navigator.geolocation.getCurrentPosition(success.bind(this), error);
}
}
The specific error message reads as TypeError: Cannot read property 'data' of undefined, pointing to daily: result.daily.data
. Despite defining daily
as an array, I am puzzled by this TypeError. For reference, this is the response format.
Prior to using JSONP due to CORS limitations, I successfully implemented similar functionality with Axios.
This was the functioning Axios code:
var _this = this;
this.serverRequest = axios.get(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`)
.then(result => {
_this.setState({
daily: result.data.daily.data,
hourly: result.data.hourly.data,
hourlySum: result.data.hourly,
dailySum: result.data.daily,
loading: false,
error: null
});
})
Thank you in advance.