Access to object attributes in visualization reaction method

I wrote a small reaction component that extracts some data from an open weather api. The extraction succeeds and I can get the json object in the response.

Then I save this response in component state using this.setState({})

And the dev response tools show that the prediction object is the actual stored state.

However, when I come to rendering any of the data, I always get the error "Can't read" forecast "of the null property.

Below is the reaction component and a screen shot of the object itself.

  export default class Weather extends Component { getWeather () { var self = this; fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c') .then (function (response) { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } response.json().then(function(data) { self.setWeather(data); }); }) .catch (function (err) { console.log('Fetch Error :-S', err); }); } setWeather (forecast) { console.log(forecast); this.setState({ forecast: forecast.name }) } componentWillMount () { this.getWeather(); } componentDidMount () { // window.setInterval(function () { // this.getWeather(); // }.bind(this), 1000); } render() { return ( <h1>{this.state.forecast}</h1> ) } } 

And this is the data object itself, right now I'm just trying to access the name attribute.

enter image description here

+7
json object fetch reactjs
source share
1 answer

It looks like you forgot a couple of things so that Component to setState you need to bind it to this preferably in the constructor. You also need to set the initial state, in your case, an empty object, and you can save the entire answer in the object and access only the parts that you want. look:

 export default class Weather extends Component { constructor() { super(); this.state = { forecast: {} }; this.setWeather = this.setWeather.bind(this); } getWeather () { let self = this; fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c') .then (function (response) { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } response.json().then(function(data) { self.setWeather(data); }); }) .catch (function (err) { console.log('Fetch Error :-S', err); }); } setWeather (forecast) { this.setState({ forecast: forecast }); } componentWillMount() { this.getWeather(); } render() { const { forecast } = this.state; return ( <h1>{forecast.name}</h1> ) } } 
+3
source share

All Articles