Reputation: 25
I am building a Weather Application, and I need to seperate the Weather card into its own component. So far, while I had the Weather card in my Weather.js
file it has been working good. But now I have seperated the Weather card into its own component but I cannot access the state.
This is my main component where I have my state:
export default class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: [],
selectedValue: ''
};
}
componentDidMount() {
fetch("http://api.weatherapi.com/v1/forecast.json?key=ca021cd2c43544e0be7112719202206&q=kosovo&days=3")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={this.state}/>
)
}
}
This is the other component that I am trying to use the state
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{this.props.items.location.country}</span>
</div>
)
}
The error that I get is: undefined has no properties
Upvotes: 1
Views: 45
Reputation: 517
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={items}/>
)
}
And in your weather component
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{props.items.location.country}</span>
</div>
)
Upvotes: 1
Reputation: 1464
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={this.state}/>
)
}
change to
render() {
const { error, isLoaded, items } = this.state;
return (
<WeatherCard items={items}/>
)
}
and
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{this.props.items.location.country}</span>
</div>
)
}
change to this
const WeatherCard = (props) => {
return (
<div>
<h2>Today</h2>
<span>{props.items.location.country}</span>
</div>
)
}
Upvotes: 0