Skip to content

Instantly share code, notes, and snippets.

@staylor
Created October 12, 2018 19:20
Show Gist options
  • Save staylor/32b0884eca2aa9cb1554e9e50bbdbbc8 to your computer and use it in GitHub Desktop.
Save staylor/32b0884eca2aa9cb1554e9e50bbdbbc8 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import fetch from 'fetch-jsonp';
const cache = {};
export default class Weather extends Component {
parseWeather = data => {
// removed for brevity
};
fetchWeather() {
const { fullCity, weatherKey } = this.props;
const city = encodeURIComponent(fullCity);
if (cache[city]) {
this.parseWeather(cache[city]);
} else {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${weatherKey}`)
.then(response => response.json())
.then(data => {
cache[city] = { ...data };
this.parseWeather(data);
})
.catch(() => {
this.parseWeather({});
});
}
}
componentDidMount() {
this.fetchWeather();
}
componentDidUpdate(prevProps) {
if (prevProps.fullCity !== this.props.fullCity) {
this.fetchWeather();
}
}
render() {
// removed for brevity
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment