|
| 1 | +import React, { Component } from 'react' |
| 2 | +import { Query } from 'react-apollo' |
| 3 | +import gql from 'graphql-tag' |
| 4 | +import IconButton from '@material-ui/core/IconButton' |
| 5 | +import MyLocation from '@material-ui/icons/MyLocation' |
| 6 | + |
| 7 | +const kelvinToCelsius = kelvin => Math.round(kelvin - 273.15) |
| 8 | +const kelvinToFahrenheit = kelvin => |
| 9 | + Math.round((kelvin - 273.15) * (9 / 5) + 32) |
| 10 | + |
| 11 | +class CurrentTemperature extends Component { |
| 12 | + state = { |
| 13 | + lat: null, |
| 14 | + lon: null, |
| 15 | + gettingPosition: false, |
| 16 | + displayInCelsius: true |
| 17 | + } |
| 18 | + |
| 19 | + requestLocation = () => { |
| 20 | + this.setState({ gettingPosition: true }) |
| 21 | + window.navigator.geolocation.getCurrentPosition( |
| 22 | + ({ coords: { latitude, longitude } }) => { |
| 23 | + this.setState({ lat: latitude, lon: longitude, gettingPosition: false }) |
| 24 | + } |
| 25 | + ) |
| 26 | + } |
| 27 | + |
| 28 | + toggleDisplayFormat = () => { |
| 29 | + this.setState({ |
| 30 | + displayInCelsius: !this.state.displayInCelsius |
| 31 | + }) |
| 32 | + } |
| 33 | + |
| 34 | + render() { |
| 35 | + const dontHaveLocationYet = !this.state.lat |
| 36 | + |
| 37 | + return ( |
| 38 | + <div className="Weather"> |
| 39 | + <Query |
| 40 | + query={TEMPERATURE_QUERY} |
| 41 | + skip={dontHaveLocationYet} |
| 42 | + variables={{ lat: this.state.lat, lon: this.state.lon }} |
| 43 | + > |
| 44 | + {({ data, loading }) => { |
| 45 | + if (loading || this.state.gettingPosition) { |
| 46 | + return <div className="Spinner" /> |
| 47 | + } |
| 48 | + |
| 49 | + if (dontHaveLocationYet) { |
| 50 | + return ( |
| 51 | + <IconButton |
| 52 | + className="Weather-get-location" |
| 53 | + onClick={this.requestLocation} |
| 54 | + color="inherit" |
| 55 | + > |
| 56 | + <MyLocation /> |
| 57 | + </IconButton> |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + const kelvin = data.weather.main.temp |
| 62 | + const formattedTemp = this.state.displayInCelsius |
| 63 | + ? `${kelvinToCelsius(kelvin)} °C` |
| 64 | + : `${kelvinToFahrenheit(kelvin)} °F` |
| 65 | + |
| 66 | + return ( |
| 67 | + <IconButton onClick={this.toggleDisplayFormat}> |
| 68 | + {formattedTemp} |
| 69 | + </IconButton> |
| 70 | + ) |
| 71 | + }} |
| 72 | + </Query> |
| 73 | + </div> |
| 74 | + ) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +const TEMPERATURE_QUERY = gql` |
| 79 | + query TemperatureQuery { |
| 80 | + weather(lat: $lat, lon: $lon) |
| 81 | + @rest( |
| 82 | + type: "WeatherReport" |
| 83 | + path: "weather?appid=4fb00091f111862bed77432aead33d04&{args}" |
| 84 | + ) { |
| 85 | + main |
| 86 | + } |
| 87 | + } |
| 88 | +` |
| 89 | + |
| 90 | +export default CurrentTemperature |
0 commit comments