Search code examples
javascriptreactjsrequestfetch-apiopenweathermap

API request infinity. Why?


I create weather application and use API openweathermap. I fetch data from API, but network in console show infinity request.

My React code:

class CityWeather extends Component {
  constructor(props){
    super(props)
    this.state = {
      city: "",
      temp: "",
      date: "Today"
    }
  }

  render() {
    const fetchWeatherData = location => {
        const url = 'http://api.openweathermap.org/data/2.5/forecast?q='+location+'&units=metric&APPID=65ea63d33ba78059603a85cba8c80620';
        fetch(url).then(res =>
          res.json()
        ).then(data => {
          this.setState({
            city: data.city.name,
            temp: data.list[0].main.temp
          })
        })
      }

    return (
      <div>
        {fetchWeatherData(this.props.name)}
        <div>{this.state.city}</div>
        <div>{this.state.date}</div>
        <div>{this.state.temp}</div>

      </div>
    )
  }
}

Solution

  • You're fetching the weather data each time a render happens. When you get a response you change the state of the component via setState, which causes a re-render, and therefore results in an infinite loop.

    Please see this post aswell: what is right way to do API call in react js?

    Instead you should be fetching the weather data when the component mounts, which only happens once. See componentDidMount in the docs.

    class CityWeather extends Component {
        constructor(props){
            super(props)
            this.state = {
                city: "",
                temp: "",
                date: "Today"
            }
        }
    
        componentDidMount() {
            const fetchWeatherData = location => {
                const url = 'http://api.openweathermap.org/data/2.5/forecast?q='+location+'&units=metric&APPID=65ea63d33ba78059603a85cba8c80620';
                fetch(url)
                    .then(res => res.json())
                    .then(data => {
                        this.setState({
                            city: data.city.name,
                            temp: data.list[0].main.temp
                        })
                    })
            };
            fetchWeatherData(this.props.name);
        }
    
        render() {
            return (
                <div>
                    <div>{this.state.city}</div>
                    <div>{this.state.date}</div>
                    <div>{this.state.temp}</div>
                </div>
            )
        }
    }