0

Trying to return weatherMsg which is a string created from a request to weather API. It is correctly requesting the weather as shown by console log.

What is return is the initial value of '' instead.

class Weather extends React.Component {
    render() {
        let request = require('request');

        let apiKey = process.env.REACT_APP_WEATHER_API_KEY;
        let city = process.env.REACT_APP_WEATHER_CITY;
        let url = `http://api.openweathermap.org/data/2.5/weather?id=${city}&units=imperial&appid=${apiKey}`

        let weatherMsg = '';

        request(url, function (err, response, body) {
        if(err){
            console.log('error retrieving weather');
        } else {
            let weather = JSON.parse(body);
            console.log(weather);
            weatherMsg = "It's {this.state.weather.main.temp} degrees in {this.state.weather.name}.";
        }
        });

        return(
            <div>{weatherMsg}</div>
        )
    }
}
liqenw
  • 15
  • 4
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – melpomene Jul 30 '19 at 05:08

1 Answers1

0

You can store the weather data in state.

let request = require('request');

class Weather extends React.Component {
    constructor(props) {
        super(props);
        this.state = { weatherMsg: '' }; 
    }

    componentDidMount () {
        let apiKey = process.env.REACT_APP_WEATHER_API_KEY;
        let city = process.env.REACT_APP_WEATHER_CITY;
        let url = `http://api.openweathermap.org/data/2.5/weather?id=${city}&units=imperial&appid=${apiKey}`

        request(url, function (err, response, body) {
        if(err){
            console.log('error retrieving weather');
        } else {
            let weather = JSON.parse(body);
            console.log(weather);
            this.setState({weatherMsg: "It's {weather.main.temp} degrees in {weather.name}."});
        }
        }.bind(this));

    }
    render() {
        return(
            <div>{this.state.weatherMsg}</div>
        )
    }
}

The problem with your code is you are not storing the weather data in state, Because of that react is not able to detect the change in your component.

liqenw
  • 15
  • 4
Rinkesh Golwala
  • 979
  • 1
  • 7
  • 17