LoginSignup
0
1

More than 1 year has passed since last update.

【OpenWeatherMap】天気予報アプリ(React × TypeScript)

Posted at

こちら↑↑の記事を参考にしました。

Weather.tsx
import React, { useState } from "react";
const APIKEY = process.env.REACT_APP_API_OPEN_WEATHER_API_KEY;

const Weathre = () => {
  const [city, setCity] = useState("");
  const [result, setResult] = useState<any>({});
  const getWeather = async (e) => {
    e.preventDefault();
    if (!city) {
      return;
    }
    const res = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKEY}`
    );
    const { main } = await res.json();
    setResult(main);
  };
  return (
    <div>
      <form onSubmit={getWeather}>
        <div>
          <label>city</label>
          <input value={city} onChange={(e) => setCity(e.target.value)} />
        </div>
        <button type="submit">get weather</button>
      </form>
      {result && (
        <div>
          <p>feels like: {result.feels_like}</p>
          <p>humidity: {result.humidity}</p>
          <p>pressure: {result.pressure}</p>
          <p>temperature: {result.temp}</p>
          <p>high: {result.temp_max}</p>
          <p>low: {result.temp_min}</p>
        </div>
      )}
    </div>
  );
}

export default Weather;

API_KEY.envファイルにて管理しています。

0
1
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
0
1