Es básicamente lo que dice el título, mi cadena de plantilla en la URL está formateada directamente con la entrada del usuario, y si el usuario ingresa incorrectamente, el intento / captura debería detectarlo y devolver un 404 y debería registrar en la consola "Error" mientras también devuelve " Error" en la pantalla, pero no lo hace, el Componente pasa de todos modos
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;Como no es un error, devolverá una Promesa. La API de Promise propone lo siguiente:
Así será :
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) })Por API de obtención :
La Promesa devuelta por
fetch()no se rechazará en estado de error HTTP incluso si la respuesta es HTTP404o500. En cambio, se resolverá normalmente (con el estado ok establecido en falso) y solo se rechazará en caso de falla de la red o si algo impidió que se completara la solicitud.
fetch('https://httpstat.us/404') .then(function(){ console.log('200 OK'); }).catch(function(){ console.console.log('404'); })El código anterior no se encontrará con el bloque catch.
Puedes hacer algo como esto:
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; }); }Puedes leer más aquí github/fetch/issues/203