I am facing the error TypeError: Cannot read properties of undefined (reading 'map')
This code should return the name of the city in a card title which is defined in my other file but throwing an error.
Codes:
import React, {Component} from 'react';
import Body from './Body';
class Weather extends Component {
constructor(props) {
super(props);
this.state = {
weather: [],
};
}
async componentDidMount() {
const url = `http://api.weatherapi.com/v1/current.json?key=${this.props.api}&q=Jaipur&aqi=no`;
let data = await fetch(url);
let parsedData = await data.json();
this.setState({
weather: parsedData.weather,
});
}
render() {
return (
<div className="container">
<div className="row">
{this.state.weather.map((element) => {
return (
<div className="col-md-4">
<Body city={element.location.name} />
</div>
);
})}
</div>
</div>
);
}
}
export default Weather;
parsedData.weatherthat you are updatingthis.state.weatherto? Is it an array?parsedData. From what I can tell,this.state.weatheris a defined array on the initial render, so somehow after you fetch data and update state,this.state.weatheris no longer defined. This is why you can't read.mapor.lengthand an error is thrown. If I had yourthis.props.apivalue I'd just reproduce this myself and see what the response value is.