im trying to build a weather app and i have been defined buttons to change the city name state and fetch the new city weather info by changing the dependency list of the useEffect hook and console log it for checking frst. but the problem is that the state is updating two steps behind the buttons that i click.
Main component for states and fetching data:
function App() {
const [cityName, setCityName] = useState('Toronto')
const [weather, setWeather] = useState('')
const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=5476766e86450fff39da1502218a3376`
const getData = () => {
axios.get(url).then((res) => {
setWeather(res.data);
});
console.log(weather)
}
useEffect(()=>{
getData()
},[])
return <div className="bg-slate-600">
<Topbuttons setCityName={setCityName} getData={getData} />
<Inputs setCityName={setCityName} getData={getData} />
<Data weather={weather} />
</div>;
}
export default App;
Im sending the setCity to the buttons component as a prop. nevermind the getData() being repeated in useEffect its just for test
buttons component:
function Topbuttons({setCityName,getData}) {
const cities = ['Tehran', 'Paris', 'Newyork', 'Berlin', 'London']
return (
<div className='flex mx-auto py-3 justify-around space-x-8 items-center text-white text-l font-bold'>
{cities.map((v,i) => {
return <button
key={i}
onClick={()=>{
console.log(v)
setCityName(v)
getData()
}}>
{v}
</button>
})}
</div>
)
}
export default Topbuttons
thanks for your help