JSFiddle - React, Tailwind, and code Playground
by Chintan Soni
HTML
<div class="mainContainer">
<h1>Current Conditions for:</h1>
<div id="loadMask">Loading...
</div>
<div>
<span id="cityName" class="dohide"></span>
</div>
<div>
<span id="temperature" class="dohide"></span>
</div>
<div>
<img id="weatherPic" class="dohide" alt="Not available" />
</div>
<div>
<span id="weatherWord" class="dohide"></span>
</div>
<div>
<span id="errorEle" class="doerror"></span>
</div>
</div>
CSS
.mainContainer {
height: 250px;
margin: 0 auto;
text-align: center;
background-color: bisque;
border: solid 1px;
padding: 5px;
border-radius: 10px;
}
.dohide {
visibility: hidden;
}
.doerror {
color: red;
}
JavaScript
var Weather = function() {
this.dataUrl = 'https://weathersync-zimbra.herokuapp.com/';
this.loadMask = document.getElementById('loadMask');
this.cityName = document.getElementById('cityName');
this.temperature = document.getElementById('temperature');
this.weatherPic = document.getElementById('weatherPic');
this.weatherWord = document.getElementById('weatherWord');
this.errorEle = document.getElementById('errorEle');
this.init();
};
/**
* Function which serve as the entry point and will start fetching data.
*/
Weather.prototype.init = function() {
var self = this;
// First, get latitude and longitude
this.fetchLongLat()
.then(function(parsedObject) {
// Now, we have latitude and longitude, get the weather information
self.fetchWeather(parsedObject.location).then(function(weatherData) {
// weather data arrived, update the UI components
self.updateUI(weatherData);
});
}).catch(function(error){
errorEle.innerHTML = error.message;
self.hideLoadMask();
});
}
/**
* Function to make request to get data from server.
* @param {String} requestUrl The url to locate required data.
* @return {Promise} Promise object returned by fetch method.
*/
Weather.prototype.fetchData = function(requestUrl) {
// Make request to given url
return fetch(requestUrl)
.then(function(response) {
if (response.ok) {
// Create and return Promise intance with parsed JSON data
return Promise.resolve(response.json());
} else {
return Promise.reject(new Error('Error fetching data'));
}
});
};
/**
* Function to get latitude and longitude.
* @return {Promise} Promise object returned by fetch method.
*/
Weather.prototype.fetchLongLat = function() {
return this.fetchData(this.dataUrl + 'ip');
};
/**
* Function to get weather information based on location dara.
* @param {Object} location The object containing location values.
* @return {Promise} Promise object...