shawtky
shawtky

Reputation: 15

React state don't re-render

I am calling api and getting response then setting response data to state. Problem is state is still undefined after setState and does not update Weather component with api data

class App extends React.Component {
  state = {
    temperature: undefined,
    icon: undefined,
    time: undefined,
    timezone: undefined,
    description: "123"
  };

  getWeather = async e => {
    e.preventDefault();
    const location = e.target.elements.city.value;
    const api_call = await fetch(`${GEO_API_URL}${location}`);
    const lngLat = await api_call.json();
    console.log(lngLat);

    const api_call2 = await fetch(
      `${API_URL}${lngLat.latitude},${lngLat.longitude}/?lang=sl&units=si`
    );
    const forecast = await api_call2.json();
    console.log(forecast);

    this.setState = {
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary
    };
    console.log(this.state.temperature);
  };

  render() {
    return (
      <div>
        <Form getWeather={this.getWeather} />

        <Weather
          temperature={this.state.temperature}
          icon={this.state.icon}
          time={this.state.time}
          timezone={this.state.timezone}
          description={this.state.description}
        />
      </div>
    );
  }
}
export default App;

Upvotes: 0

Views: 78

Answers (3)

Kondrat Shmoylov
Kondrat Shmoylov

Reputation: 27

And additionally, to a previous comments I would recommend refreshing the setState understanding from official documentation https://reactjs.org/docs/react-component.html#setstate

Upvotes: 0

Trần C&#244;ng
Trần C&#244;ng

Reputation: 298

Using the right format for the setState method.

this.setState({field: 'new value'});

Now Change the code setState like.

 this.setState({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

Upvotes: 0

Shubham J.
Shubham J.

Reputation: 646

Try using

 this.setState({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

instead of

  this.setState = ({
      temperature: forecast.currently.temperature,
      icon: forecast.currently.icon,
      time: forecast.currently.time,
      timezone: forecast.timezone,
      description: forecast.currently.summary,
});

Upvotes: 4

Related Questions