I am working on a weather app project. I have three cities right now with a select tag. My purpose is that when a user selects another city, I try to pass it into my API call. But, even though there is no error, the API call works later. I mean when the user selects Y city, the API call shows the previous, for instance, X. When the user switches it into Z city, the API call shows Y city not Z city. And I do not think that aysnc function causes this because without async, it still works in the same way. How can I make them sync?
This is the line my API call exists:
useEffect(() => {
async function fetchApi() {
const res = await axios(`https://api.openweathermap.org/data/2.5/forecast?q=${getSelection}&appid=c681e6e33ec339728fdf88e0b24a2a01`)
setTakeData(res.data)
}
fetchApi()
}, [])
This is the component where "getSelection" comes from:
function Header() {
const [selection, setSelection] = useState({value: "Ankara"})
const cities = ["?stanbul", "Ankara", "?zmir"]
const handleSelection = (e) => {
setSelection({value: e.target.value})
return (
<div>
<div className="header">
<select name="selection" value={selection.value} onChange={handleSelection}>
<option value="?stanbul">{cities[0]}</option>
<option value="Ankara">{cities[1]}</option>
<option value="?zmir">{cities[2]}</option>
</select>
</div>
<ApiCall getSelection={selection.value} />
</div>
)
This is the console:
This is from header.jsx: ?zmir
This is from ApiCall.jsx: ?zmir
UPDATED CITY: Istanbul
This is from ApiCall.jsx: ?zmir
UPDATED CITY: Istanbul
This is from ApiCall.jsx: ?zmir
UPDATED CITY: Istanbul
This is from ApiCall.jsx: ?zmir
UPDATED CITY: Istanbul
This is from ApiCall.jsx: ?zmir
UPDATED CITY: ?zmir
As you see, it is updated at the last.