Skip to content

Instantly share code, notes, and snippets.

@iamalvisng
Created January 15, 2017 14:30
Show Gist options
  • Save iamalvisng/ef5366e194c0436977dcf5e4c6097f31 to your computer and use it in GitHub Desktop.
Save iamalvisng/ef5366e194c0436977dcf5e4c6097f31 to your computer and use it in GitHub Desktop.
class App extends Component {
constructor(props) {
super(props);
this.state = {
location: 'Loading...',
temp: null,
icon: '01d',
unit: 'C',
isMetric: true,
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isMetric: !prevState.isMetric,
unit: !prevState.unit,
temp: () => {
if (prevState.isMetric === true) {
return {
temp: prevState.temp * 9/5 + 32,
}
}
}
}));
}
componentDidMount() {
const weatherData = () => {
axios.get(GEO_IP_API)
.then(pos => {
let lat = pos.data.latitude;
let lon = pos.data.longitude;
axios.get(`${OPEN_WEATHER_URL}lat=${lat}&lon=${lon}&units=${TEMP_UNITS}&appid=${API_KEY}`)
.then(res => {
console.log(res.data);
this.setState({
location: res.data.name,
temp: res.data.main.temp,
icon: res.data.weather[0].icon,
});
})
.catch(err => {
console.log(err);
});
});
}
weatherData();
}
render() {
return (
<div>
<div>
{this.state.location}
</div>
<div>
{this.state.temp}&deg;{this.state.unit ? 'C' : 'F'}
</div>
<div>
<img src={`${ICON_URL}${this.state.icon}${ICON_FORMAT}`} alt="Icon" />
</div>
<button onClick={this.handleClick}>
{this.state.isMetric ? '°C' : '°F'}
</button>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment