I am working on a weather app project in React as a beginner. I am using OpenWeatherAPI in that case.
My problem is when I try to use forEach, it gives an error as it seems below.
ApiCall.jsx:15 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
Here is my Header component:
import ApiCall from './ApiCall';
function Header() {
const cities = ["İstanbul", "Ankara", "İzmir"]
return (
<div>
<div className="header">
<select name="selection">
<option value="istanbul">{cities[0]}</option>
<option value="ankara">{cities[1]}</option>
<option value="izmir">{cities[2]}</option>
</select>
</div>
<ApiCall getCities={cities} />
</div>
)
}
export default Header
And this is my ApiCall component:
import axios from "axios"
import { useEffect, useState } from "react"
function ApiCall({ getCities }) {
const[data, setData] = useState([])
useEffect(() => {
axios(`https://api.openweathermap.org/data/2.5/forecast?q=${selectCity}&appid=c681e6e33ec339728fdf88e0b24a2a01`)
.then(res => setData(res.data))
.catch(err=> console.log(err))
})
const { city, list } = data
const selectCity = getCities.array.forEach((element) => {
if (city.name === element) {
return element
}
});
return (
null
)
}
export default ApiCall
All answers will be appreciated.
CodePudding user response:
The foreach should be like this
getCities.forEach
Instead of
getCities.array.forEach
What do you think ?
If getCities is an array , you have to use forEach on it instead of using .array.forEach
CodePudding user response:
It seems that you try to filter all the available cities with the cities you are getting as property to your component (getCities
).
Since getCities
is an array you can directly call the forEach
function on it and loop over the cities but since you want to apply a filter I think you are better off using Javascript's build-in filter method.
const selectCity = getCities.filter((possibleCityName) => {
return city.name === possibleCityName)
});