i am new in React, i have a begginer question I can’t solved it.
I have a simple Input and Button to get data from API.
// function to handleChange
const [searchQuery, setSearchQuery] = useState('')
const [getCityData, setGetCityData] = useState('');
const [cityData, setCityData] = useState([]);
const handleChange = (e) => {
setSearchQuery(e.target.value)
}
// function to handle button get City from API
const handleClick = () => {
if (searchQuery !== "") {
try {
setGetCityData(searchQuery);
fetchCity();
} catch (error) {
console.log(error);
}
}
}
// function to get data from API
const fetchCity = async () => {
try {
const res = await axios.get(url)
console.log(res.data);
setCityData(res.data);
console.log(cityData);
} catch (error) {
console.log(error);
}
}
The problem is, when I press the button after fill the input, it always log with empty array first.
First line is data from API, the second line is log from function
and when fill the input with another City, it display the previous data.
I think when we fetch the city it did not update the latest value.
How we fix this? or how we ‘delay’ the request API after useState is fill with the latest value.
Thank you for your attention.
2
Answers
The issue you’re facing is due to the asynchronous nature of the
fetchCity
function. When you call it, it starts executing in the background, but the code below it continues to run immediately, without waiting for the API call to finish.To fix this, you can use the
useEffect
hook in React to watch for changes in thesearchQuery
state variable. WheneversearchQuery
changes, you can then call thefetchCity
function to get the updated data.Here’s an updated version of your code that should resolve the issue:
In this updated code, we use the
useEffect
hook to listen for changes to thegetCityData
state variable. WhenevergetCityData
changes (i.e., when the button is clicked and the state is set), thefetchCity
function is called to fetch the data from the API.This ensures that the API call is made only after the
getCityData
state has been updated with the latest value.i don’t know how you are generating the url on axios get method and passing the search query in the request, it seems like you are passing along with url.
Try this method by passing query as a param to the fetchCity function and add it with the baseurl