Home > other >  React class component state value not updating
React class component state value not updating

Time:01-08

I am new to react js. I am learning it by creating a simple app. I tried to create a simple weather app using react class component. All working fine but the result stored in a state variable is not printing in the template. I can see the API response in the console and then store the result on the 'currWeatherRes' state variable which is not showing in the template (Location is always blank)

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  
  constructor(){
    super();

    this.state = {
        cityName: "",
        currWeatherRes: {}
    }
}

  handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was:`  this.state.cityName);

      fetch(`https://api.openweathermap.org/data/2.5/weather?q=` this.state.cityName `&appid=f3ee66722740d00cc6f197cbcab3d534`, {
        method: 'GET'
      }).then((response) => {
        console.log(response)
        this.setState({
          currWeatherRes: response
        })
        //return response.json();
      });
  }

  handleChange = (event) => {
    this.setState({cityName:event.target.value});
  }

  render() {
    return (
      <div className="weather-app">
          <form onSubmit={this.handleSubmit}>
            <input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
            <button type="submit" value="Submit">Submit</button>
          </form>
          {(typeof this.state.currWeatherRes.main != "undefined") ? (
              <div className="weather-details">
                  <div className="weather-location">
                      <div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
                  </div>
              </div>
          ):('')}
      </div>
    );
  }
}

export default App;

CodePudding user response:

The problem was not related to react but the way you handled API call.

Fix:

fetch(`https://api.openweathermap.org/data/2.5/weather?q=` this.state.cityName `&appid=f3ee66722740d00cc6f197cbcab3d534`, {
        method: 'GET'
      }).then((response) => {
        return response.json();
      }).then((res) => {
        this.setState({
          currWeatherRes: res
        })
      });

Working code:

import React, { Component } from 'react';


class App extends Component {
  
  constructor(){
    super();

    this.state = {
        cityName: "",
        currWeatherRes: {}
    }
}

  handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was:`  this.state.cityName);

      fetch(`https://api.openweathermap.org/data/2.5/weather?q=` this.state.cityName `&appid=f3ee66722740d00cc6f197cbcab3d534`, {
        method: 'GET'
      }).then((response) => {
        return response.json();
      }).then((res) => {
        this.setState({
          currWeatherRes: res
        })
      });
  }

  handleChange = (event) => {
    this.setState({cityName:event.target.value});
  }

  render() {
    console.log(this.state.currWeatherRes)
    return (
      <div className="weather-app">
          <form onSubmit={this.handleSubmit}>
            <input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
            <button type="submit" value="Submit">Submit</button>
          </form>
          {(typeof this.state.currWeatherRes.main != "undefined") ? (
              <div className="weather-details">
                  <div className="weather-location">
                      <div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
                  </div>
              </div>
          ):('')}
      </div>
    );
  }
}

export default App;

  •  Tags:  
  • Related