Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from "react";
- import WeatherCard from "./components/WeatherCard/component";
- import "./App.css";
- function App() {
- const [query, setQuery] = useState("Sydney, au");
- const [weather, setWeather] = useState({
- temp: null,
- city: null,
- condition: null,
- country: null,
- });
- // fetch the openweather api data
- const data = async (q) => {
- const apiResponse = await fetch(
- `https://api.openweathermap.org/data/2.5/weather?q=${weather.city}&units=metric&appid=KEYHERE`
- );
- const responseJson = await apiResponse.json();
- return responseJson;
- };
- // search after button is pressed only
- const handleSearch = (e) => {
- //stop the button doing it's normal / default action
- e.preventDefault();
- data(query).then((res) => {
- setWeather({
- temp: res.main.temp,
- city: res.name,
- condition: res.weather[0].main,
- country: res.sys.country,
- });
- });
- };
- // render elements to screen
- return (
- <div className="App">
- <WeatherCard
- temp={weather.temp}
- condition={weather.condition}
- city={weather.city}
- country={weather.country}
- />
- <form>
- <input value={query} onChange={(e) => setQuery(e.target.value)} />
- // when clicking, call the handleSearch function
- <button onClick={(e) => handleSearch(e)}>Search</button>
- </form>
- </div>
- );
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement