Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. import React, {Component} from 'react';
  2. import { getLocationCoords, getWeatherData } from './api';
  3.  
  4. export default class WeatherApp extends Component {
  5. constructor() {
  6. super();
  7. this.state = {
  8. city: 'Loading...',
  9. country: 'Loading...',
  10. currentWeather: 'Loading...',
  11. currentTemperature: 0,
  12. currentUnit: 'C',
  13. availableUnit: 'F'
  14. };
  15. this.componentDidMount = this.componentDidMount.bind(this);
  16. }
  17. componentDidMount() {
  18. this.fetchWeather(this.state.currentUnit);
  19. }
  20. fetchWeather(units) {
  21. getLocationCoords().then(
  22. (coords) => {
  23. // Got location data, get weather now
  24. getWeatherData(units, coords ).then(
  25. (weatherData) => {
  26. // Got weather data, proceed to update state using setState()
  27. console.log(weatherData.name);
  28. this.setState({
  29. city: weatherData.body.name,
  30. country: weatherData.body.sys.country,
  31. currentTemperature: weatherData.body.main.temp,
  32. currentWeather: weatherData.body.weather[0].main,
  33. currentUnit: units,
  34. availableUnit: units === 'C' ? 'F' : 'C'
  35. });
  36. document.querySelector('body').className = getWeatherClass(weatherData.body.weather[0].id);
  37. }, (error) => {
  38. // Could not get weather data.
  39. console.log(error);
  40. }
  41. );
  42. }, (error) => {
  43. // Couldn't get location data.
  44. console.error(error);
  45. }
  46. );
  47. function getWeatherClass(code) {
  48. if (code >= 200 && code < 300) {
  49. return 'thunderstorm';
  50. } else if (code >= 300 && code < 400) {
  51. return 'drizzle';
  52. } else if (code >= 500 && code < 600) {
  53. return 'rain';
  54. } else if (code >= 600 && code < 700) {
  55. return 'snow';
  56. } else if (code >= 700 && code < 800) {
  57. return 'atmosphere';
  58. } else if (code === 800) {
  59. return 'clear';
  60. } else if (code >= 801 && code < 900) {
  61. return 'clouds';
  62. } else if (code >= 900 && code < 907) {
  63. return 'extreme';
  64. } else if (code >= 907 && code < 1000) {
  65. return 'additional';
  66. } else {
  67. return 'unknown';
  68. }
  69. }
  70. }
  71. render() {
  72. return (
  73. <div className="main-wrapper overlay">
  74. <div className="forecast-box">
  75. <h1 className="city-name">{this.state.city}</h1>
  76. <h2 className="country">{this.state.country}</h2>
  77. <h3 className="temperature">{this.state.currentTemperature} &#176; {this.state.currentUnit} <span
  78. className="super-small" onClick={this.fetchWeather.bind(this, this.state.availableUnit)}> / {this.state.availableUnit} </span></h3>
  79. <h2>{this.state.currentWeather}</h2>
  80. </div>
  81. </div>
  82. );
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement