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

6
  • You mentioned an object is returned, but you're checking for array by using the posts.length. Could you please share the response? Commented Sep 18, 2021 at 23:50
  • I added a screenshot of the response. Commented Sep 19, 2021 at 0: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 ways to check if the object is empty. Commented Sep 19, 2021 at 0:09
  • Any idea why the component won't render? Commented Sep 19, 2021 at 0:13
  • when you're running this code, {Object.keys(posts).length ? <div>Temperature: {posts.main.temp} Description: {posts.weather[0].description}</div> : null}, its still rendering nothing on the screen? Commented Sep 19, 2021 at 0:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.