Created
March 26, 2018 08:52
-
-
Save iremlopsum/98de215354e8e01ea12d4b0c8bb6b632 to your computer and use it in GitHub Desktop.
This file contains 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 { Line } from 'react-chartjs-2'; | |
import './app.scss'; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
labels: [], | |
temps: [], | |
minTemp: 10, | |
maxTemp: 30, | |
timeout: 3000, | |
} | |
this.addRandomData = this.addRandomData.bind(this); | |
} | |
componentDidMount() { | |
const url = 'https://api.openweathermap.org/data/2.5/weather?q=München,DE&units=metric&appid=382aa7ad3501c6d4a564022372982343'; | |
setTimeout(() => { | |
fetch(url).then((res) => { | |
if (res.status !== 200) { | |
console.log('Looks like there was a problem. Status Code: ' + res.status); | |
return; | |
} | |
res.json().then((resJson) => { | |
let { temps, labels } = this.state; | |
temps.push(resJson.main.temp); | |
labels.push(`${new Date().getHours()}:${new Date().getMinutes()}`); | |
this.setState({ temps, labels }, () => { | |
this.addRandomData() | |
}) | |
}) | |
}).catch((err) => { | |
console.log('Fetch Error :-S', err); | |
}) | |
}, 10) | |
} | |
getRandomTemp(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
addRandomData() { | |
let { temps, labels, timeout } = this.state; | |
temps.push(this.getRandomTemp(this.state.minTemp, this.state.maxTemp)); | |
labels.push(`${new Date().getHours()}:${new Date().getMinutes()}`); | |
this.setState({ temps, labels }) | |
setTimeout(() => { | |
this.addRandomData(); | |
}, timeout) | |
} | |
renderGraph() { | |
const { temps, labels } = this.state; | |
console.log(temps) | |
const data = { | |
labels: labels, | |
datasets: [{ | |
label: 'temprature', | |
fill: false, | |
backgroundColor: 'rgba(75,192,192,0.4)', | |
borderColor: 'rgba(75,192,192,1)', | |
borderCapStyle: 'butt', | |
borderDash: [], | |
borderDashOffset: 0.0, | |
borderJoinStyle: 'miter', | |
data: temps, | |
events: ['click'] | |
}] | |
} | |
return ( | |
<Line | |
data={data} | |
/> | |
) | |
} | |
render() { | |
return ( | |
<div className="app"> | |
{this.renderGraph()} | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment