LoginSignup
3
3

More than 3 years have passed since last update.

React Axios による OpenWeatherMap API の実行例

Last updated at Posted at 2019-09-20

前回の記事で React の開発環境を構築しました。環境が整ったので次は Restful API の呼び出しを学習してみます。ここで紹介する OpenWeatherMap は、ユーザー登録してAPIキーを入手する必要がありますが、キーさえあればCORS(Cross-Origin Resource Sharing)制約なしにリクエストを受け付けてくれるのでダイレクトに呼び出してデータを取得できます。

サインアップは以下から行います。
https://openweathermap.org/

サインアップ後は以下URLで自分のAPIキーが参照できます。
https://home.openweathermap.org/api_keys

今回はAPIの呼び出しに Axios モジュールを使用するのでローカルにインストールします。

npm i --save-dev axios

前回の記事にあるApp.jsを元に以下の様に改変します。"YOUR_API_KEY" の箇所は、openweathermapのサイトで表示された自分のAPIキーに変更します。

import React from 'react';
import axios from "axios";

const API_ENDPOINT = 'http://api.openweathermap.org/data/2.5/forecast';

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            apiKey : 'YOUR_API_KEY',
            requestCity: '',         //  ex. 'Tokyo,jp'
            city: '',
            response : []
        };
        this.handleInput = this.handleInput.bind(this);
        this.handleGetWeather = this.handleGetWeather.bind(this);
    }
    handleGetWeather(){
        axios
            .get(API_ENDPOINT, {
                params: {
                    q: this.state.requestCity,
                    APPID: this.state.apiKey
                } })
            .then(res => {
                this.setState({
                    response: res.data.list,
                    city: res.data.city.name
                });
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    handleInput({ target: { value } }) {
        this.setState({
            requestCity: value
        });
    }
    render() {
        console.log(this.state.response);

        return (
            <div>
                <h1>Weather forecast</h1>
                <input type="text" value={this.state.requestCity} onChange={this.handleInput} />
                <button onClick={this.handleGetWeather}>Search</button>
                <p> Location: {this.state.city} </p>
                {Object.keys(this.state.response).map(key => (
                    <li key={key}>
                        {this.state.response[key].dt_txt}
                        ,<img src={'http://openweathermap.org/img/w/'+this.state.response[key].weather[0].icon+'.png'} />
                        {this.state.response[key].weather[0].main}
                    </li>
                ))}
            </div>
        );
    }
}

編集が終わったら、スクリプト実行します。

npm run start

テキスト・フィールドに Tokyo 等の都市や市区町村名を入れて Search ボタンをクリックすると以下の様に3時間毎の天気予報がリスト表示されます。

Weather report
Location: Tokyo

2019-09-20 09:00:00,Clear
2019-09-20 12:00:00,Clouds
2019-09-20 15:00:00,Clouds
2019-09-20 18:00:00,Rain
2019-09-20 21:00:00,Rain
2019-09-21 00:00:00,Rain
2019-09-21 03:00:00,Clouds
2019-09-21 06:00:00,Clouds
2019-09-21 09:00:00,Clouds
2019-09-21 12:00:00,Rain
2019-09-21 15:00:00,Clouds
2019-09-21 18:00:00,Clouds
2019-09-21 21:00:00,Clouds
2019-09-22 00:00:00,Clouds
2019-09-22 03:00:00,Clouds
2019-09-22 06:00:00,Clouds
2019-09-22 09:00:00,Rain
2019-09-22 12:00:00,Rain
2019-09-22 15:00:00,Rain
2019-09-22 18:00:00,Rain
2019-09-22 21:00:00,Clouds
2019-09-23 00:00:00,Clouds
2019-09-23 03:00:00,Rain
2019-09-23 06:00:00,Clouds
2019-09-23 09:00:00,Clouds
2019-09-23 12:00:00,Clouds
2019-09-23 15:00:00,Clouds
2019-09-23 18:00:00,Clouds
2019-09-23 21:00:00,Clouds
2019-09-24 00:00:00,Clouds
2019-09-24 03:00:00,Clouds
2019-09-24 06:00:00,Clouds
2019-09-24 09:00:00,Clouds
2019-09-24 12:00:00,Clouds
2019-09-24 15:00:00,Clouds
2019-09-24 18:00:00,Clouds
2019-09-24 21:00:00,Clouds
2019-09-25 00:00:00,Clouds
2019-09-25 03:00:00,Clouds
2019-09-25 06:00:00,Clouds
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3