Created
October 28, 2023 12:04
-
-
Save ajunquit/029d69aa180419112caebf9decf8df49 to your computer and use it in GitHub Desktop.
Cap 8. Consuming the REST API with React: Exercise 1 - Weather API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logo from './logo.svg'; | |
import './App.css'; | |
import React, { useState } from 'react'; | |
function App() { | |
const [temp, setTemp] = useState(''); | |
const [desc, setDesc] = useState(''); | |
const [icon, setIcon] = useState(''); | |
const [isReady, setReady] = useState(false); | |
React.useEffect( () => { | |
fetch('https://api.openweathermap.org/data/2.5/weather?q=Guayaquil&units=Metric&APIkey=73b9fa8a810e1695503f5757ffcf51d2') | |
.then(result => result.json()) | |
.then(jsonResult => { | |
setTemp(jsonResult.main.temp); | |
setDesc(jsonResult.weather[0].main); | |
setIcon(jsonResult.weather[0].icon); | |
setReady(true); | |
}).catch(error => { | |
console.error(error); | |
}) | |
}) | |
if(isReady){ | |
return ( | |
<div className="App"> | |
<p>Temperature: {temp}</p> | |
<p>Description: {desc}</p> | |
<img src={`http://openweathermap.org/img/wn/${icon}@2x.png`} alt="Weather Icon" /> | |
</div> | |
); | |
}else{ | |
return <div> Loading ...</div> | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment