onChange event doesn’t return the first change of the text input but works on subsequent changes. Sorry if this is obvious, I’m new to React.
JavaScript
x
36
36
1
import React, { useState } from 'react';
2
import axios from 'axios';
3
4
function Header() {
5
6
const [text, setText] = useState("");
7
const [location, setLocation] = useState("");
8
9
function handleChange(event) {
10
setText(event.target.value);
11
}
12
13
// when submit button clicked, current state of the text input is stored inside location constant
14
function handleClick() {
15
setLocation(text);
16
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + location + "&limit=5&appid={apikey}"
17
function getCoordinates(url) {
18
axios.get(url).then((response) => {
19
const locationLat = response.data[0].lat;
20
const locationLon = response.data[0].lon;
21
22
});
23
}
24
getCoordinates(geoCoderURL);
25
}
26
return (
27
<div>
28
<h1>Five Day Forecast</h1>
29
<input onChange={handleChange} type="text" name="name"autoFocus placeholder="Enter location here."/>
30
<button type="submit" onClick={handleClick}>Forecast</button>
31
</div>
32
)
33
}
34
35
export default Header;
36
Advertisement
Answer
When you call setLocation(text);
, handleClick
will finish execution before the location
value is actually updated.
There is no need for location
and setLocation
; looks like maybe location
is supposed to be the same as text
.
JavaScript
1
11
11
1
function handleClick() {
2
const geoCoderURL = "http://api.openweathermap.org/geo/1.0/direct?q=" + text + "&limit=5&appid={apikey}"
3
function getCoordinates(url) {
4
axios.get(url).then((response) => {
5
const locationLat = response.data[0].lat;
6
const locationLon = response.data[0].lon;
7
});
8
}
9
getCoordinates(geoCoderURL);
10
}
11