input field is not updating the City useState. i tried onSubmit too, but that was resulting more errors. sometimes useEffect was refreshing the whole page when i press the submit button.
// using State for updating city
const [City, setCity] = useState();
// this function will fetch the data from Weather API, using useEffect
useEffect(() => {
console.log("updating data" );
}, [City] )
function CitySearch() {
console.log(City);
}
// taking input and updating the city, button using the city search function.
// problem: city not updating !
return (
<div>
<form>
<input onClick={Event => setCity(Event.target.value)} placeholder="Enter city name"/>
<button className="search-btn" type="submit" onClick={CitySearch} >Search</button>
</form>
</div>
)
CodePudding user response:
you are supposed to use onChange here to read the input, onClick is for click handling .
<input onChange={Event => setCity(Event.target.value)} placeholder="Enter city name"/>
and for to stop reloading the form submit you can use preventdefault on the event , not exactly sure what you are doing after the submit calling api on the search probably.
CodePudding user response:
Try this:
const [city, setCity] = useState("");
// this function will fetch the data from Weather API, using useEffect
const updateData = (event) => {
let yourWrittenCityName = event.target.value;
console.log(yourWrittenCityName);
//update your data here from Api
};
const CitySearch = () => {
console.log(city);
};
return (
<div>
<form>
<input
value={city}
onChange={(e) => setCity(e.target.value)}
onBlur={(e) => updateData(e)}
placeholder="Enter city name"
/>
<div onClick={CitySearch}>Search</div>
</form>
</div>
);
To update a input value, you should use "value" property and "onChange" function from input.
Then you can use "onBlur" to do something when the user finish to writte the name of the city and leaves the input.
Good luck