I'm working with react and a weather API and have put together this form:
function Forecast() {
const [cities, setCities] = React.useState([]);
const addCity = (city) => {
if (!city.text || /^\s*$/.test(city.text)) {
return;
}
const newCities = [city, ...cities];
setCities(newCities);
};
const removeCity = (id) => {
const removedArray = [...cities].filter((city) => city.id !== id);
setCities(removedArray);
};
return (
<div>
<Form onSubmit={addCity} />
</div>
);
}
const Form = (props) => {
const api = {
key: "39471307bd579e5ce6b1d89dc164dd77",
base: "https://api.openweathermap.org/data/2.5/",
};
const [input, setInput] = React.useState("");
const [weather, setWeather] = React.useState({});
const [query, setQuery] = React.useState("");
const handleChange = (e) => {
setInput(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
fetch(`${api.base}weather?q=${input}&appid=${api.key}&units=metric`)
.then((res) => res.json())
.then((result) => setWeather(result));
props.onSubmit({
id: Math.floor(Math.random() * 10000),
text: input,
data: weather,
});
setInput("");
};
return (
<form className="search-container" onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter City"
name="text"
value={input}
className="search"
onChange={handleChange}
/>
<button className="add-card-button">
<i className="fas fa-plus-circle"></i>
</button>
</form>
);
};
ReactDOM.render(<Forecast />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
When I'm testing this, the first time you search for a city it's returning no data and the second time you search, it's using the input from the first search as so on. Does anyone know how can I get it so that the first search returns data immediately?