I'm new to React and wanted to fetch API.The idea is: when I click a button then it should first change a state and then fetch data. Now is not working how I expected... when I click the button it displays data from 4 cites(because of init state) and then I click particular city (eg. Tampere) but after clicking nothing happens yet, when I click another button (eg Helsinki) it display me data from previous clicked button(Tampere city)....How to fix it? I use console.log for displaying data because it's just testing. I'd appreciate if you can have a look at my components. Thank you!
App.js and DropBar.js
------------------
//main component in App.js file
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cityId: '658225,655195,650225,634964&units=metric',
multi: 'group'
}
}
getWeather = ({ currentTarget }) => {
fetch(`http://api.openweathermap.org/data/2.5/${this.state.multi}?id=${this.state.cityId}&appid=${API_KEY}`)
.then(response => response.json())
.then(data => {
this.setState({
cityId: currentTarget.id,
multi: currentTarget.value
})
console.log(data);
});
};
render() {
return (
<MainLayout>
<div className="App">Hello!</div>
<DropBar getWeather={this.getWeather} />
</MainLayout>
);
}
}
export default App;
------------------
//Buttons component in DropBar.js file
const DropBar = (props) => {
return (
<form >
<Button id="634964" value="weather" onClick={props.getWeather}>Click Tampere!</Button>
<Button id="658225" value="weather" onClick={props.getWeather}>Click Helsinki!</Button>
<Button id="655195" value="weather" onClick={props.getWeather}>Click Jyvaskila!</Button>
<Button id="650225" value="weather" onClick={props.getWeather}>Click Kuopio!</Button>
<Button
id="658225,655195,650225,634964&units=metric"
value="group"
onClick={props.getWeather}
>
All kaupungit!
</Button>
</form>
);
}
export default DropBar;```
first change a state and then fetch dataif you want to make state reflect the fetched datasetStateis async. This means you cannot console log the updated values immediately after setting it. The update doesn't happen right away. If you console.log inside the render method, you will see the correct values.