Its basically what the title says, my template string in the URL is formatted directly with user input, and if the user inputs incorrectly, the try/catch should catch it and return a 404 and it should console log "Error" while also returning "Error" on the screen, but it doesn't, the Component passes through anyways
import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-solid-svg-icons'
function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('Paris')
const [weatherData, setWeather] = useState([])
const [error, setError] = useState(false)
const getWeather = async() =>{
setLoading(true)
setError(false)
try{
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=imperial`)
const pResp = await resp.json()
setWeather(pResp)
setLoading(false)
}
catch(err){
console.log("ERRRRROOOORRRR")
setError(true)
}
}
const handleSubmit = (e) =>{
e.preventDefault()
console.log(city)
getWeather()
}
useEffect(()=>{
getWeather()
},[])
if(loading==true){
return <>
<h1 className='title'>Monkey Wit Da Weather</h1>
<Loading/>
}
else if(error===true){
return<>
<h1>Error</h1>
</>
}
else{
return<>
<h1 className='title'>Monkey Wit Da Weather</h1>
<Daily {...weatherData} setCity={setCity} city={city} getWeather={getWeather} handleSubmit={handleSubmit}/>
</>
}
}
export default App;
Because it is not an error, it will return a Promise. The Promise API proposes the following:
So it will be :
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=imperial`).then(response => {
console.log("response:", response)
}).catch(error => {
console.log("error:", error)
})
Per Fetch API:
The Promise returned from
fetch()won't reject on HTTP error status even if the response is an HTTP404or500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
fetch('https://httpstat.us/404')
.then(function(){
console.log('200 OK');
}).catch(function(){
console.console.log('404');
})
Above code it won't run into catch block.
You can do something like this:
class FetchError extends Error {
constructor(response) {
super(`HTTP error ${response.status}`);
this.response = response;
}
}
function fetchSomething(...args) {
return fetch(...args)
.then(response => {
if (!response.ok) {
throw new FetchError(response);
}
return response;
});
}
You can read more here github/fetch/issues/203