Estoy aprendiendo React y, como práctica, estoy creando una aplicación meteorológica.
Todo está bien. pero quiero que cuando un usuario escriba el nombre de una ciudad, por ejemplo, 'Londres', haga clic en el botón Buscar y obtenga los datos. la próxima búsqueda si es 'londres' (que actualmente está visible) no quiero que mi función handleGetData llame al servidor para obtener datos.
¿Cómo se debe implementar esta lógica? ¿Qué debo cambiar? Apreciaré su ayuda
import React, { Component } from "react"; import InputSearch from "./common/inputSearch"; import http from "../services/httpService"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import Weather from "./weather"; class App extends Component { state = { city: { name: "", info: [], }, }; handleChange = (e) => { const city = this.state.city; city.name = e.currentTarget.value; this.setState({ city }); }; handleGetData = async () => { try { const city = this.state.city; const apiEndPoint = `http://api.weatherapi.com/v1/forecast.json?key=97de37820e0e4a29b9c90051221604&q=${city.name}&days=3&aqi=no&alerts=no`; const { data } = await http.get(apiEndPoint); city.info = data; this.setState({ city }); } catch (e) { const expectedError = e.response.status && e.response.status > 400 && e.response.status < 500; if (expectedError) { toast.error("Something failed while getting Data"); } } }; render() { const { city } = this.state; return ( <React.Fragment> <ToastContainer /> <InputSearch stateCityName={city.name} onChanges={this.handleChange} onGettingData={this.handleGetData} /> <Weather data={city.info} data2={city} /> </React.Fragment> ); } } export default App;Puede usar un nuevo estado como su búsqueda anterior y compararlo con su búsqueda actual
Es algo como esto, pero no lo probé, así que es posible que tengas que hacer alguna modificación.
state = { city: { name: "", info: [], }, previousSearch: "", }; handleChange = (e) => { const city = this.state.city; prevCity = city.name; city.name = e.currentTarget.value; this.setState({ city, previousSearch: prevCity }); }; handleGetData = async () => { try { const city = this.state.city; if(previousSearch !== city.name) { const apiEndPoint = `http://api.weatherapi.com/v1/forecast.json?key=97de37820e0e4a29b9c90051221604&q=${city.name}&days=3&aqi=no&alerts=no`; const { data } = await http.get(apiEndPoint); city.info = data; this.setState({ city }); } } catch (e) { const expectedError = e.response.status && e.response.status > 400 && e.response.status < 500; if (expectedError) { toast.error("Something failed while getting Data"); } } };Que te diviertas