Created
October 12, 2018 19:20
-
-
Save staylor/32b0884eca2aa9cb1554e9e50bbdbbc8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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