Magda Aderibigbe
Magda Aderibigbe

Reputation: 3

how to setState with fetch API on click button in React

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;```


Upvotes: 0

Views: 2549

Answers (1)

Jay
Jay

Reputation: 3107

Please use setState callback

getWeather = ({ currentTarget }) => {
  this.setState({
    cityId: currentTarget.id,
    multi: currentTarget.value
  }, () => {
    fetch(`http://api.openweathermap.org/data/2.5/${this.state.multi}?id=${this.state.cityId}&appid=${API_KEY}`)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      });
  })
};

Upvotes: 2

Related Questions