Reputation: 61
I'm building an app in React. I'm new to React so please bear with me. This question is very simple. I am creating three components that are being called by an API (I'm using axios to call the API), but they simply won't render. I am not sure what I'm doing wrong.
import React, { Component } from "react";
import axios from "axios";
class Temperature extends Component {
showTemperature = () => {
let apiKey = "4cc79448ae57aa2b8557ec4dcd604fac";
let city = "Lisbon,pt";
let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
axios.get(url).then(function(response) {
let temp = Math.round(response.data.main.temp);
return temp;
});
};
render() {
return <div>{this.showTemperature()}</div>;
}
}
export default Temperature;
and then I call the component on App.js
<div>
<Temperature />
</div>
inside the App function. Nothing is rendering when I call the component. Any tips or what am I doing wrong? Thanks.
PS: I am importing the components into App:
import Temperature from "./Temperature";
EDIT: I want to add that I have this same app done in vanilla JavaScript and the API is working fine.
Upvotes: 1
Views: 490
Reputation: 3299
Try utilizing state to store your temperature value, like so:
import React, { Component } from "react";
import axios from "axios";
class Temperature extends Component {
constructor(props) {
super(props);
this.state = {
temp: 'Error' // Add default value to help determine if error is api call.
};
this.showTemperature = this.showTemperature.bind(this); // Bind 'this' context
}
showTemperature() { // This is how to properly declare a method in react.
let apiKey = "4cc79448ae57aa2b8557ec4dcd604fac";
let city = "Lisbon,pt";
let url = `https://api.openweathermap.org/data/2.5/weather?
q=${city}&appid=${apiKey}&units=metric`;
axios.get(url).then(function(response) {
let temp = Math.round(response.data.main.temp);
if (temp) { // Don't setstate if temp is undefined.
this.setState({temp: temp}); // Set your state
}
});
};
componentDidMount() {
this.showTemperature(); // Call your method on mount.
}
render() {
return <div>{this.state.temp}</div>;
}
}
export default Temperature;
I added comments to explain further errors in your code. You should be able to troubleshoot much better from here.
Upvotes: 1
Reputation: 5226
Your showTemperature method returns undefined. That's why It's not rendering anything.
Upvotes: 0
Reputation: 9
You have to import Temperature in App.js like this
import Temperature from 'path'
Upvotes: 0