Advertisement
irishstorm

App.js

Apr 13th, 2020
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useSate, useState, useEffect } from "react";
  2. import "./App.css";
  3. import WeatherCard from "./components/WeatherCard/WeatherCard";
  4.  
  5. function App() {
  6.   const location = "Enniscorthy, IE";
  7.   const [query, setQuery] = useState("");
  8.   const [loading, setLoading] = useState(false);
  9.  
  10.   const [weather, setWeather] = useState({
  11.     temp: null,
  12.     city: null,
  13.     condition: null,
  14.     country: null,
  15.   });
  16.  
  17.   const getWeather = async (query) => {
  18.     setLoading(true);
  19.     const res = await fetch(
  20.       `https://api.openweathermap.org/data/2.5/weather?q=${query}&units=metric&APPID=398370e94f7cfbf0edb8e0120b1e06cb`
  21.     );
  22.  
  23.     const resJson = await res.json();
  24.     setWeather({
  25.       temp: resJson.main.temp,
  26.       city: resJson.name,
  27.       condition: resJson.weather[0].main,
  28.       country: resJson.sys.country,
  29.     });
  30.  
  31.     setLoading(false);
  32.   };
  33.  
  34.   const handleSearch = (e) => {
  35.     e.preventDefault();
  36.     getWeather(query);
  37.   };
  38.  
  39.   useEffect(() => {
  40.     getWeather(location);
  41.   }, [location]);
  42.  
  43.   return (
  44.     <div className="App">
  45.       {!loading ? (
  46.         <div>
  47.           <WeatherCard
  48.             tempature={weather.temp}
  49.             condition={weather.condition}
  50.             city={weather.city}
  51.             country={weather.country}
  52.           ></WeatherCard>
  53.           <form>
  54.             <input value={query} onChange={(e) => setQuery(e.target.value)} />
  55.             <button onClick={(e) => handleSearch(e)}>Search</button>
  56.           </form>
  57.         </div>
  58.       ) : (
  59.         <div style={{ colour: "black" }}>loading</div>
  60.       )}
  61.     </div>
  62.   );
  63. }
  64.  
  65. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement