Skip to content Skip to sidebar Skip to footer

Open Weather Data In React Using Ajax

Given the Open Weather Map current weather data API, I'm trying to pull in current weather data into my React.js app using ajax, extract the current temp value for a given city, an

Solution 1:

There might be some errors with this, but I think it should get you pretty close.

varReact = require("react");
var $ = require("jquery");

varCity = React.createClass({
    propTypes: {
        id: React.PropTypes.string.isRequired,
        units: React.PropTypes.string
    },

    getInitialState: function () {
        return {
            data: {},
            fetching: false
        };
    },

    getDefaultProps: function () {
        return {
            units: "imperial"
        };
    },

    render: function () {
        return (
            <divclass="city">
                {this.state.fetching ? "Downloading data..." : this.state.data.main.temp}
            </div>
        );
    },

    componentWillMount: function () {
        $.ajax({
            url: "http://api.openweathermap.org/data/2.5/weather?id="+this.props.id+"&units="+this.props.units,
            dataType: "json",
            beforeSend: function () {
                this.setState({fetching: true});
            },
            success: function (data) {
                this.setState({data: data});
            },
            error: function (xhr, status, err) {
                console.error(xhr, status, err.toString());
            },
            complete: function () {
                this.setState({fetching: false});
            },
            context: this
        });
    }
});

varCityGrid = React.createClass({
    propTypes: {
        cityIds: React.PropTypes.array.isRequired
    },

    renderCity: function (cityId) {
        return<Cityid={cityId} />;
    },

    render: function () {
        return (
            <divclass="city-grid">
                {this.props.cityIds.map(this.renderCity)}
            </div>
        );
    }
});

That being said... this isn't The Right Solution. The ajax call should be moved outside of the component (have you looked into Flux, or some other library that would give you the concept of a Model or a Store?), the returned "data" should then be transformed/normalized into a flat structure somehow, and then passed to the City component as props (and only the props that make sense/that you care about). This way, the City component can be agnostic about where its data comes from. You should, in theory, be able to render a City with some data from another source, multiple sources, dummy data, etc. But I wasn't going to go and code all that for you ;)

Solution 2:

Before you setState on data, this.state.data is undefined. You can fix this by either not rendering anything from this.state.data until it's defined, or set data: {} in your getInitialState.

Post a Comment for "Open Weather Data In React Using Ajax"