Advertisement
Guest User

Weather.js

a guest
Nov 20th, 2019
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect } from "react";
  2. import axios from "axios";
  3. import countryStyles from "./country.module.scss";
  4.  
  5. const Weather = ({ country }) => {
  6.   //initial state for weather
  7.   const [weather, setWeather] = useState("");
  8.   const [displayWeather, setDisplayWeather] = useState(false);
  9.  
  10.   //using API with the specific country capital name for weather as per docs
  11.   useEffect(() => {
  12.     const key = `68af2c5582e650e0dc1c65f6c3717d65`;
  13.     const url = `https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${key}&units=metric`;
  14.  
  15.     axios.get(url).then(response => {
  16.       // console.log("response.data: ", response.data);
  17.       setWeather(response.data); //updating state based off JSON values
  18.       setDisplayWeather(true); //updating state
  19.     });
  20.   }, [country.capital]); //we want to only fetch data when the component mounts -> the effect depends on the query so when changed, data request is fired
  21.  
  22.   //using conditional flow; a) if init state of displayWeather is true, show the details b) loading/fetching data
  23.   return (
  24.     <div>
  25.       {!displayWeather ? (
  26.         <p>Please wait...</p>
  27.       ) : (
  28.         <div>
  29.           <h3>Weather in {country.capital}</h3>
  30.           <p>
  31.             <span className={countryStyles.detail}>Current temperature:</span>{" "}
  32.             {weather.main.temp}c
  33.           </p>
  34.           <p>
  35.             <span className={countryStyles.detail}>Min temp:</span>{" "}
  36.             {weather.main.temp_min}c
  37.           </p>
  38.           <p>
  39.             <span className={countryStyles.detail}>Max temp:</span>{" "}
  40.             {weather.main.temp_max}c
  41.           </p>
  42.           <p>
  43.             {" "}
  44.             <span className={countryStyles.detail}>Conditions: </span>
  45.             {weather.weather[0].description}
  46.           </p>
  47.  
  48.           <p>
  49.             <span className={countryStyles.detail}>Wind: </span>{" "}
  50.             {weather.wind.speed} kph with a direction of {weather.wind.deg}{" "}
  51.             degrees
  52.           </p>
  53.           <p>
  54.             <span className={countryStyles.detail}>Cloud coverage:</span>{" "}
  55.             {weather.clouds.all}%
  56.           </p>
  57.           <p>
  58.             <span className={countryStyles.detail}>Humidity:</span>{" "}
  59.             {weather.main.humidity}%
  60.           </p>
  61.         </div>
  62.       )}
  63.     </div>
  64.   );
  65. };
  66.  
  67. export default Weather;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement