0

I cannot figure out what I am doing wrong here. I submit a request to the API and an object is returned, but I cannot seem to get the component to render.

//Code

import React, { Component } from "react"
import axios from 'axios';

class Weather extends Component {
  constructor(props){
    super(props)
      this.state = {
        posts: [],
    };
  }

  componentDidMount() {
    const query = "Paris";
    const apiKey = {api key here};
    const unit = "metric";
    const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
    axios.get(`${url}`)
      .then(response => {
          console.log(response);
          this.setState({posts: response.data})

      })
      .catch(error => {
          console.log(error);
      })
  }

  render() {
    const { posts } = this.state;
    return(
        <>
          {posts.length ? <div>Temperature: {posts.main.temp} Description: {posts.weather[0].description}</div> : null}
        </>
    );
  }
}

export default Weather;

enter image description here

General Grievance
  • 4,555
  • 31
  • 31
  • 45
czarcb
  • 1
  • 2
  • You mentioned an object is returned, but you're checking for array by using the `posts.length`. Could you please share the `response`? – Junaid Faryad Sep 18 '21 at 23:50
  • I added a screenshot of the response. – czarcb Sep 19 '21 at 00:03
  • Thanks for sharing. Yeah, the `data` is a object and you can check for an empty object using `Object.keys(posts).length`. There are also some [other](https://stackoverflow.com/questions/42813784/javascript-check-if-object-is-empty) [ways](https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) to check if the object is empty. – Junaid Faryad Sep 19 '21 at 00:09
  • Any idea why the component won't render? – czarcb Sep 19 '21 at 00:13
  • when you're running this code, `{Object.keys(posts).length ?
    Temperature: {posts.main.temp} Description: {posts.weather[0].description}
    : null}`, its still rendering nothing on the screen?
    – Junaid Faryad Sep 19 '21 at 00:16
  • That resolved it!! Thank you so much!! :) – czarcb Sep 19 '21 at 00:27

0 Answers0