Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState } from "react";
  2.  
  3. import WeatherCard from "./components/WeatherCard/component";
  4. import "./App.css";
  5.  
  6. function App() {
  7.   const [query, setQuery] = useState("Sydney, au");
  8.   const [weather, setWeather] = useState({
  9.     temp: null,
  10.     city: null,
  11.     condition: null,
  12.     country: null,
  13.   });
  14.  
  15.   // fetch the openweather api data
  16.   const data = async (q) => {
  17.     const apiResponse = await fetch(
  18.       `https://api.openweathermap.org/data/2.5/weather?q=${weather.city}&units=metric&appid=KEYHERE`
  19.     );
  20.  
  21.     const responseJson = await apiResponse.json();
  22.     return responseJson;
  23.   };
  24.  
  25.   // search after button is pressed only
  26.   const handleSearch = (e) => {
  27.     //stop the button doing it's normal / default action
  28.     e.preventDefault();
  29.     data(query).then((res) => {
  30.       setWeather({
  31.         temp: res.main.temp,
  32.         city: res.name,
  33.         condition: res.weather[0].main,
  34.         country: res.sys.country,
  35.       });
  36.     });
  37.   };
  38.  
  39.   // render elements to screen
  40.   return (
  41.     <div className="App">
  42.       <WeatherCard
  43.         temp={weather.temp}
  44.         condition={weather.condition}
  45.         city={weather.city}
  46.         country={weather.country}
  47.       />
  48.       <form>
  49.         <input value={query} onChange={(e) => setQuery(e.target.value)} />
  50.         // when clicking, call the handleSearch function
  51.         <button onClick={(e) => handleSearch(e)}>Search</button>
  52.       </form>
  53.     </div>
  54.   );
  55. }
  56.  
  57. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement