So, I'm getting stuck into React and it's already making me scratch my head..
I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!
Here is the main component:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = [];
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
When I use console.log(result[0]);
it simply outputs as "undefined" in the console.
I am trying to assign all values to the results variable and then push it to the state.
When I do console.log(items) it shows all items as well which is very odd.
API data
Any help would be deeply appreciated!
Thanks